Java Exception

Introduction

There are certain events that sometimes return an unexpected result or return no result. These types of events are known as exceptions.

In java, an exception is an event that interrupts the normal flow of the program to give an abnormal result or no result.

Let’s try understanding it with the help of an example

Code:

Java Code

public class Main {
  public static void main(String args[]) {
    int a = 0;
    int b = 2;
    System.out.println(b / a);
  }
}

Output:

How to handle this?

A method can handle the exception by itself or pass it to the initializer but at some point the handling of these exceptions is necessary.

You don’t have to worry since Java has an exception handling feature that handles runtime errors such as IOException, etc.

Types of Exception

Exceptions are divided into two types:

  1. Built-in Exceptions
    1. Checked Exception 
    2. Unchecked Exception
  2. User-Defined Exceptions

Built-in Exceptions

Exceptions that are predefined in JAVA are known as built-in exceptions.

Checked Exception

  • This exception is also known as I/O Exceptions
  • These exceptions are checked during compile time.
  • Some of the examples are:
    • Trying to read from a file that never existed.
    • Trying to read a file that has got no contents or the pointer points to the EOF.

Explaining this with the help of an example – suppose you are trying to read from a file that never existed. The exception raise would be FileNotFoundException

Code:

Java Code

import java.io.File;
import java.io.FileReader;
public class Main {

  public static void main(String args[]) {
    File file = new File("E://tuf.txt");
    FileReader fr = new FileReader(file);
  }
}

Output:

Unchecked Exception

  • This exception is also known as runtime exceptions.
  • These exceptions are checked during runtime.
  • Some of the examples are:
    • Trying to access illegal locations in an array or going out of bounds.
    • Dividing a number by 0. 

To understand this, we take an example where we choose an index in our array which doesn’t exist.

Code:

Java Code

public class main {
   public static void main(String args[]) {
      int num[] = {1, 2, 3, 4};
      System.out.println(num[5]);
   }
}

Output:

User-defined Exception

Java gives permission to the programmer to write their own exception and even throw it.

There are certain rules which a programmer should keep in mind while writing his/her own exception which is as follows:

  1. All the exceptions must be the child of throwable class.
  2. To write a checked exception, you need to extend the exceptions class.
  3. To write a runtime exception, you need to extend the RuntimeException class.

The following syntax can be used while defining our own Exception class

Syntax:

Class myException extends Exception{
	//code
}

Let’s try building our own exception.
We would build a program that would check the age limit. If the age is greater or equal to 18, then the program should print “You are eligible” otherwise it should throw an exception and print the stack trace.

Code:

Java Code

import java.io.*;

// creating our own exception
class AgeLimitException extends Exception {
  private int age;
  public AgeLimitException(int age) {
    this.age = age;
  }
}
// using our exception
class AgeChecker {
  private int age;
  public void Age(int age) {
    this.age = age;
  }
  public void AgeCheck(int age) throws AgeLimitException {
    if (age >= 18) {
      System.out.println("You are eligible");
    } else {
      throw new AgeLimitException(age);
    }
  }
}
// invoking our function which would throw an exception
class main {
  public static void main(String args[]) {
    AgeChecker ag = new AgeChecker();
    try {
      ag.AgeCheck(14);
    } catch (AgeLimitException agex) {
      System.out.println("You are not eligible");
      agex.printStackTrace();
    }
  }
}

Summarizing the above code, we are performing the following steps:

  1. Creating our exception by extending the exception class. This would make it a checked exception.
  2. Creating a function that would throw our exception.
  3. Invoking the function which would throw our exception.

Special thanks to Yash Mishra for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this articleIf you want to suggest any improvement/correction in this article please mail us at [email protected]