Throwing and Catching Exception in Java

Throwing and catching exceptions in Java is a fundamental part of Java Exception Handling. The throw statement is used to throw an exception, and the trycatch block is used to catch and handle exceptions.

Here’s an example that demonstrates throwing and catching an exception:

public class Example {
    public static void main(String[] args) {
        try {
            int x = divide(10, 0);
        } catch (ArithmeticException e) {
            System.out.println("Caught exception: " + e);
        }
    }

    public static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Cannot divide by zero");
        }
        return a / b;
    }
}

In this example, the divide method throws an ArithmeticException if the second argument b is 0. The main method calls the divide method with arguments 10 and 0, which causes an ArithmeticException to be thrown. The trycatch block in the main method catches the exception and prints a message to the console.

The output of the above code will be:

Caught exception: java.lang.ArithmeticException: Cannot divide by zero

Here’s a breakdown of the code:

  • The divide method takes two arguments a and b.
  • If b is 0, the divide method throws an ArithmeticException with the message “Cannot divide by zero”.
  • The main method calls the divide method with arguments 10 and 0.
  • The trycatch block in the main method catches the ArithmeticException that was thrown by the divide method and prints a message to the console.

🗒 Note:

It’s important to note that not all exceptions need to be caught. If an exception is not caught, it will propagate up the call stack until it is caught by a higher-level exception handler or the program terminates. In the example above, if the ArithmeticException was not caught in the main method, it would propagate up the call stack until it was caught by the JVM or the program terminated.

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