Java Exception Handling

In the previous article, we studied the type of exceptions that occur in java and also tried building our own exception. In this article, we’ll try to understand how we can manage those exceptions.

As we know, handling exceptions is really important as they may produce abnormal output or try pointing it to the programmer that there is something weird in your code.

Let’s assume that if an exception is not handled in the program, then when the program gets executed, then the exception message will print with the help of the uncaught exception handler.

Java supports robust exception handling mechanisms. It permits us to handle the exception by using keywords like try, catch, finally, throw, and throws.

When an uncaught exception occurs, JVM calls the private method dispatchUncaughtException().

Generally, programmers want to handle the exception in their own way instead of trusting the default exception handler. They don’t want the program to terminate but to handle the exception carefully while the program executes.

To handle exceptions, we can use the following keywords present in Java:

  1. Try
  2. Catch
  3. Throw
  4. Throws
  5. finally

The article would proceed with an explanation of each keyword and the code related to it for better understanding. In the end, we’ll combine every keyword to make a full-fledged exception handling program.

Try block

  • Try block is the starting point for handling exceptions.
  • A code that may produce an exception is placed in the try block.
  • Generally, we use to try and catch blocks in pairs.
  • A single try block can’t be executed without having at least one catch block.
  • The following syntax works for the try block:
try {
  // exception generating code
}

Catch block

  • Catch block contains the code which immediately executes if the exception is produced and caught carefully.
  • Catch block also specifies the exception type. If the generated exception matches the specified exception, the exception is successfully caught.
  • Following syntax works for the catch block
catch (exception type) {
  // code
}

Try-catch block

  • Try-catch blocks are generally used in pairs for proper handling of the exception code.
  • Let’s see the code below for a better understanding.

Code:

Java Code

public class Main {
  public static void main(String args[]) {
    try {
      int c = 4 / 0;
      System.out.println(c);
    } catch (ArithmeticException ae) {
      System.out.println("Division with 0 is not possible + ae");
    }
  }
}

Output:

Division with 0 is not possible + ae

In the above program, we are handling the code where we are dividing a number by 0. Once an exception is encountered in the try block, the control is transferred to the catch block where exception matching is done. Once the exception matches with the specified exception type, the exception object is received in reference variable ae.

Later the code within the catch block is executed.

Note: In the above program, we are also printing the exception object ae which displays the exception information in output.

Throw

  • The throw keyword is used to throw any checked or unchecked exceptions.
  • It is mainly used to throw a custom exception.
  • We can also define our own conditions and throw exceptions. For example, we can throw ArithematicException when we divide by any number instead of 0.
  • The syntax for throw would be as follows:
throw new exception_class(“message”);

Let’s try understanding the throw keyword using an example

Code:

Java Code

public class MyClass {
  public static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("You are not eligible");
    } else System.out.println("You are eligible");
  }
  public static void main(String args[]) {
    checkAge(12);
  }
}

Output:

Here we built a program that would check the age for eligibility. You may notice that if the age is smaller than 18, we are throwing an ArithmeticException with the message You are not eligible. This is the beauty of the throw keyword.

Throws keyword

  • When the programmer doesn’t want to handle the exception on his own and wants to pass it to the caller of that method, he/she can use the throws keyword.
  • It is generally used to handle the checked exception.
  • throws keyword also declares the exception and reports it to the compiler.
  • There is no guarantee that the exception would be handled properly.
  • The syntax for this keyword would be:
Return_type method_name() throws ExceptionClass {
//code
}

Code:

Java Code

public class MyClass {
    public static void main(String args[]) {
        for(int i=0;i<5;i++){
            System.out.println("TUF");
            Thread.sleep(1000);
        }
    }
}

Output:

As you can see, the compiler itself asks the programmer to catch the exception or pass it to the caller (here passing to the caller is referred to as throws). Here the caller is JVM since it is executing the Daemon thread which is present in the main class.

We can handle this manually by ourselves by using the try-catch block but we use the throws keyword to get this exception handled by the JVM.

Code:

Java Code

public class MyClass {
  public static void main(String args[]) throws InterruptedException {
    for (int i = 0; i < 5; i++) {
      System.out.println("TUF");
      Thread.sleep(1000);
    }
  }
}

Output:

TUF
TUF
TUF
TUF
TUF

Finally

  • finally keyword is super useful when we need to execute a code that was not able to execute due to an exception.
  • It’s completely optional to write finally keyword.
  • finally block doesn’t bother about the exception nor does it care about the try and the catch block.
  • The syntax would be as follows:
finally {
  //code
}

Code:

Java Code

public class MyClass {
  public static void main(String args[]) {
    try {
      int c = 3 / 0;
      System.out.println(c);
    } catch (ArithmeticException ae) {
      System.out.println("Exception handled" + ae);
    } finally {
      System.out.println("Finally block code");
    }
  }
}

Output:

Exception handledjava.lang.ArithmeticException: / by zero
Finally block code

Here we are handling the exception which is generated by dividing by 0. Once the exception is handled, we are executing a code that would be executed after the exception.

Using all these methods we can handle and even manipulate the exception according to our needs and to maintain the normal flow of the program.

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]