- 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.
Table of Contents
Java try-catch Example
Let’s look at a simple code where we can get an exception.
package com.journaldev.examples;
public class JavaTryCatch {
public static void main(String[] args) {
System.out.println(divide(20,5));
System.out.println(divide(20,0));
}
public static double divide(int x, int y) {
return x/y;
}
}
Output:
4.0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.journaldev.examples.JavaTryCatch.divide(JavaTryCatch.java:11)
at com.journaldev.examples.JavaTryCatch.main(JavaTryCatch.java:7)
Now let’s see how to use a try-catch block to handle the exception thrown by the divide() method.
package com.journaldev.examples;
public class JavaTryCatch {
public static void main(String[] args) {
try {
System.out.println(divide(20, 5));
System.out.println(divide(20, 0));
} catch (ArithmeticException ae) {
System.out.println(ae.getMessage());
}
}
public static double divide(int x, int y) {
return x / y;
}
}
Output:
4.0
/ by zero
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.
package com.journaldev.examples;
public class JavaTryCatch {
public static void main(String[] args) {
try {
foo(10);
} catch (IllegalArgumentException ie) {
System.out.println(ie.getMessage());
} catch (NullPointerException ne) {
System.out.println(ne.getMessage());
}
}
public static void foo(int x) throws IllegalArgumentException, NullPointerException {
// some code
}
}
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.
try {
foo(10);
} catch (Exception ie) {
System.out.println(ie.getMessage());
} catch (NullPointerException ne) {
System.out.println(ne.getMessage());
}
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.
try {
foo(10);
} catch (IllegalArgumentException | NullPointerException e) {
System.out.println(e.getMessage());
}
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.
package com.journaldev.examples;
import java.io.FileInputStream;
import java.io.IOException;
public class JavaTryCatch {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("data.txt");
// code to process the file
fis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I would like to respond to your example of the try/catch/finally.
The code block is pretty big and can be improved in two ways.
Firstly, in old school Java, you could use the fis.close() ONLY in the finally block, as that is always executed.
It makes no sense to close it in the TRY block, and then check if it’s closed in the finally block, so:
try {
fis = new FileInputStream(“data.txt”);
// code to process the file
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
A better way, however, is to make use of the try-with-resources functionality of Java.
Which will automatically close the resource.
try(fis = new FileInputStream(“data.txt”)) {
// code to process the file
} catch (IOException e) {
e.printStackTrace();
}
Best regards,
Tim
Thanks for the feedback. I will add a section about it in the article.