Java exception handling with an example program

Java is a well-known programming language that can be used to create robust and dependable software applications. Even the best-written code can encounter errors or unexpected events during execution. This is where exception handling comes into play. Exception handling in Java enables developers to anticipate and gracefully handle errors, ensuring that their programs continue to run smoothly even when unexpected problems arise.

In this article, we'll look at the fundamentals of Java exception handling and provide some sample programs to get you started.

In Java, exception handling is the mechanism that allows developers to handle runtime errors or exceptions that occur during program execution. Exception handling allows a program to handle unexpected situations gracefully, preventing the program from crashing or behaving unexpectedly.

In Java, exception handling is accomplished by combining the try, catch, and finally keywords. The code in the "try" block may throw an exception, and the code in the "catch" block handles the exception. The "finally" block is optional and contains code that is executed whether or not an exception is thrown.

In general, exception handling in Java entails using a try-catch along with the finally block, as shown below:

try {
   // Code block that may throw an exception
} catch (ExceptionType1 e1) {
   // ExceptionType1 exception handler
} catch (ExceptionType2 e2) {
   // ExceptionType2 exception handler
} finally {
   // Whether or not an exception was thrown, this optional block of code must be executed
}

We can have multiple "catch" blocks.

The try block in this form contains the code that may potentially throw an exception. The catch blocks define what to do when a specific type of exception is thrown, and the finally block contains code that is executed whether or not an exception is thrown.

Java exception handling example

Consider the following program as an example demonstrating the exception handling in Java:

import java.util.Scanner;

public class MyClass {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    
    System.out.print("Enter the numerator: ");
    int numerator = scanner.nextInt();
    System.out.print("Enter the denominator: ");
    int denominator = scanner.nextInt();

    try {
      int result = divide(numerator, denominator);
      System.out.println("\nResult: " + result);
    } catch (ArithmeticException e) {
      System.out.println("\nAn error occurred: " + e.getMessage());
    } catch (Exception e) {
      System.out.println("\nAn unknown error occurred: " + e.getMessage());
    } finally {
      System.out.println("\n\nProgram completed!");
    }
  }

  public static int divide(int a, int b) {
    return a / b;
  }
}

When we execute the above Java program, we will get the output shown in the snapshot given below:

java exception handling example

Now type the numerator value, let's say 12, and hit the ENTER key. Then type the denominator value, let's say 3, and hit the ENTER key to get the following output:

java exception handling program

Now if we try with a denominator value of 0, then we will get the following output:

exception handling example in Java

The divide method is wrapped in a try block because division by zero is undefined and will result in an ArithmeticException. If an ArithmeticException is thrown during the division operation, the program will use the first catch block to catch the exception and print a user-friendly error message.

If an exception of another type is thrown during the division operation, the program will catch it with the second catch block and print a generic error message. Regardless of whether an exception was thrown or not, the finally block will always be executed and will print a message indicating that the program has completed.

The following figure depicts the top-level exception hierarchy:

java exception handling

Java exception types: built-in exceptions

Here is a list of some of the more typical Java exception types along with a short description:

Java Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!