Exception Handling in Java

Exception handling is an important aspect of writing robust and reliable code in Java. It allows you to detect and recover from errors and unexpected conditions that may occur during the execution of your program. In this tutorial, we will cover the basics of Java exception handling and show you how to handle exceptions in your code.

Types of Exceptions:

Java has two types of exceptions: checked exceptions and unchecked exceptions.

  1. Checked exceptions are exceptions that are checked at compile time. This means that you must handle them in your code or declare that your method throws them. Examples of checked exceptions include FileNotFoundException and IOException.
  2. Unchecked exceptions are exceptions that are not checked at compile time. This means that you do not have to handle them in your code or declare that your method throws them. Examples of unchecked exceptions include NullPointerException and ArithmeticException.

Exception Handling in Java:

Java exception handling is done using the try-catch block. The basic syntax of the try-catch block is as follows:

try {
    // code that might throw an exception
} catch (Exception e) {
    // code to handle the exception
}

Here, the try block contains the code that might throw an exception, and the catch block contains the code to handle the exception. If an exception is thrown in the try block, the program will jump to the catch block and execute the code in there.

Handling Checked Exceptions:

When dealing with checked exceptions, you have two options. You can either handle the exception using a try-catch block or declare that your method throws the exception.

  1. Handling Checked Exceptions with a Try-Catch Block:

If you choose to handle the exception using a try-catch block, you can catch the specific exception that is thrown and handle it accordingly. For example:

try {
    FileInputStream file = new FileInputStream("file.txt");
} catch (FileNotFoundException e) {
    System.out.println("File not found.");
}

Here, we catch the FileNotFoundException that is thrown when the file file.txt cannot be found. We then print an error message to the console.

  1. Declaring Checked Exceptions:

If you choose to declare that your method throws the exception, you must add the exception to the method signature. For example:

public void readFromFile() throws IOException {
    FileInputStream file = new FileInputStream("file.txt");
}

Here, we declare that the readFromFile() method throws an IOException. This means that any code that calls this method must handle the exception or declare that it throws the exception as well.

Handling Unchecked Exceptions:

When dealing with unchecked exceptions, you do not have to declare that your method throws the exception. However, it is still a good idea to handle the exception using a try-catch block.

try {
    int x = 1 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero.");
}

Here, we catch the ArithmeticException that is thrown when we try to divide by zero. We then print an error message to the console.

A complete example of Java exception handling that involves reading input from the user and handling potential exceptions:

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("Enter a number: ");
            int num = scanner.nextInt();
            System.out.println("You entered: " + num);
        } catch (Exception e) {
            System.out.println("Invalid input: " + e.getMessage());
        } finally {
            scanner.close();
            System.out.println("Scanner closed.");
        }
    }
}

In this example, we’re using a Scanner object to read input from the user. We’re using a trycatch block to handle any exceptions that might be thrown while reading the input. And we’re using a finally block to ensure that the Scanner object is closed, regardless of whether an exception is thrown or not.

Here’s how the code works:

  • We create a new Scanner object that reads from System.in.
  • We use a trycatch block to read an integer input from the user using scanner.nextInt(). If the user enters a non-integer value, an exception will be thrown and caught by the catch block.
  • If an exception is caught, we print an error message to the console that includes the exception message using e.getMessage().
  • We use a finally block to close the Scanner object and print a message to the console indicating that the Scanner object has been closed.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author