Java try-catch Examples

Java try-catch block is used to handle exceptions in the program.

  • The code in the try block is executed and if any exception occurs, catch block is used to process them.
  • If the catch block is not able to handle the exception, it’s thrown back to the caller program.
  • If the program is not able to process the exception, it’s thrown back to the JVM which terminates the program and prints the exception stack trace to the output stream.
  • A try block must be followed by either catch or finally block.

Java try-catch Example

Let’s look at a simple code where we can get an exception.

Output:

Now let’s see how to use a try-catch block to handle the exception thrown by the divide() method.

Output:

Java try-catch Multiple Exceptions

We can catch multiple exceptions in a series of catch blocks. Let’s look at a simple example of using multiple catch blocks.

Catching Exceptions Order

Java Exceptions have a hierarchy. Throwable is the superclass of all the exceptions and errors. When catching multiple exceptions, the most specific Exception should be caught first. Otherwise, a compile-time error is thrown with the message as “Unreachable catch block. It is already handled by the catch block for Exception”.

The below code will give compile time error because NullPointerException should be caught before Exception.

Catching Multiple Exceptions in a Single catch block

If you notice the above code, we are printing the exception message in all the catch blocks. Java supports catching multiple exceptions in a single catch block. This feature was introduced in Java 7.

Java try-catch-finally Example

The finally block is always executed, even if the program throws the exception and terminates. The finally block is generally used to make sure that the resources are closed before the program terminates.

Here is a real-life example of the try-catch-finally block. We are trying to open a file and process it. We are using finally block to make sure FileInputStream is closed.

Java finally block has been deprecated because it’s not reliable. The recommended approach is to use try-with-resources to initialize and close resource automatically. You can read about it in detail at Java Try with Resources.

By admin

Leave a Reply