The catch Blocks
You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.
Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType , declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name .
The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler’s argument.
The following are two exception handlers for the writeList method:
Exception handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions, as described in the Chained Exceptions section.
Catching More Than One Type of Exception with One Exception Handler
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar ( | ):
Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final . In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.
Catching and Handling Exceptions
This section describes how to use the three exception handler components the try , catch , and finally blocks to write an exception handler. Then, the try- with-resources statement, introduced in Java SE 7, is explained. The try- with-resources statement is particularly suited to situations that use Closeable resources, such as streams.
The last part of this section walks through an example and analyzes what occurs during various scenarios.
The following example defines and implements a class named ListOfNumbers . When constructed, ListOfNumbers creates an ArrayList that contains 10 Integer elements with sequential values 0 through 9. The ListOfNumbers class also defines a method named writeList , which writes the list of numbers into a text file called OutFile.txt . This example uses output classes defined in java.io , which are covered in Basic I/O.
The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If the file cannot be opened, the constructor throws an IOException . The second boldface line is a call to the ArrayList class’s get method, which throws an IndexOutOfBoundsException if the value of its argument is too small (less than 0) or too large (more than the number of elements currently contained by the ArrayList ).
If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileWriter constructor. However, it does not display an error message about the exception thrown by get . The reason is that the exception thrown by the constructor, IOException , is a checked exception, and the one thrown by the get method, IndexOutOfBoundsException , is an unchecked exception.
Now that you’re familiar with the ListOfNumbers class and where the exceptions can be thrown within it, you’re ready to write exception handlers to catch and handle those exceptions.
Java try catch finally Blocks
Last Updated: January 29, 2022
Java try, catch and finally blocks helps in writing the application code which may throw exceptions in runtime and gives us a chance to either recover from exception by executing alternate application logic or handle the exception gracefully to report back to the user. It helps in preventing the ugly application crashes.
1. Java try, catch and finally blocks
1.1. try block
The try block contains the application code which is expected to work in normal conditions. For example, reading a file, writing to databases or performing complex business operations.
A try bock is written with try keyword followed with the curly braces.
1.2. catch block
The optional catch block(s) follows the try block and MUST handle the checked exceptions thrown by try block as well as any possible unchecked exceptions.
An application can go wrong in N different ways. That’s why we can associate multiple catch blocks with a single try block. In each catch block, we can handle one or more specific exceptions in a unique way.
When one catch block handles the exception, the next catch blocks are not executed. Control shifts directly from the executed catch block to execute the remaining part of the program, including finally block.
1.3. finally block
An optional finally block gives us a chance to run the code which we want to execute EVERYTIME a try-catch block is completed – either with errors or without any error.
The finally block statements are guaranteed of execution even if the we fail to handle the exception successfully in catch block.
1.4. only try block is mandatory
Please note that only try block is mandatory while catch and finally blocks are optional. With a try block, we can use either a catch block or finally block as needed.
It is possible to have below given both combinations in Java. Both versions are valid.
2. How java exception handling works?
Under normal circumstances, when there is an exception occurred during runtime, JVM wraps the error information in a instance of sub-type of Throwable. This exception object is similar to other Java objects and have fields and methods.
Only difference is that JVM checks their presence and pass control to catch block which can handle this exception type or it’s parent class types.
try catch finally flow
When in the application, there is no catch block found for an exception, the uncaught exception is handled by a default exception handler at JVM level. It reports the exception to user and terminate the application.
3. Different execution flows with try, catch and finally blocks
Let’s see some examples to understand how the executions will flow in different cases.
3.1. try, catch and finally blocks – NO exception occurred
If there is no exception occurred, then JVM will execute only finally block. Catch block will be skipped.
3.2. try, catch and finally blocks – exception occurred
If there is an exception occurred in try block, then JVM will execute catch block first and then finally block.
3.3. try and finally blocks – exception NOT handled
If the exception is not handled by any provided catch block, the JVM default exception handler handle it. In this case, finally block will be executed followed by default exception handling mechanism.
3.4. try, catch and finally blocks – multiple catch blocks
If there are multiple catch blocks associated with the try block, then exception is handled by the first catch block in sequence which can handle the exception type or it’s parent types.
For example, a catch block handling IOException, can handle the exceptions of type FileNotFoundException also because FileNotFoundException extends IOException .
3.5. try, catch and finally blocks – exception is thrown from catch block
There may be cases when there is an exception while handling another exception in catch block. How it will handled?
In case of exception in catch block, the execution is transferred to finally block (if any) associated with the respective catch block. Then the exception is propagated in method call stack to find a catch block which can handle this exception.
If such catch block is found then exception is handled, else JVM default exception handler handles the exception and terminates the application.
For Closeable resources, such as streams, Java SE 7 introduced try-with-resources statements which is recommended ways to handle exceptions in mentioned scenarios. In this approach, we are not required to close the streams and JVM does it for us. It eliminates the need of finally blocks.
In try-with-resources, a resource is opened in try block inside small brackets and finally block is completely gone.
Java Exceptions — Try. Catch
When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).
Java try and catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The try and catch keywords come in pairs:
Consider the following example:
This will generate an error, because myNumbers does not exist.
The output will be something like this:
If an error occurs, we can use try. catch to catch the error and execute some code to handle it:
The output will be:
The finally statement lets you execute code, after try. catch , regardless of the result:
The output will be:
You can define as many catch blocks as you want:
The throw keyword
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException , FileNotFoundException , ArrayIndexOutOfBoundsException , SecurityException , etc:
Throw an exception if age is below 18 (print «Access denied»). If age is 18 or older, print «Access granted»:
The output will be:
If age was 20, you would not get an exception:
Try Catch in Java Explained [Exception Handling Examples]
Table of Contents
Introduction to try catch exception handling in Java
Errors occur frequently while coding in any programming language. Sometimes, we may misspell a name or keyword, or sometimes we unknowingly change the symbols. These are very common and easy to handle errors. But there are some errors that are not that much easy to handle, we need a special block of codes to handle such complex errors.
In this tutorial, we will learn how we can handle different errors and exceptions in java programming using the try catch java block method. We will first learn the basic syntax of the java try and catch method and will solve some of the exceptions by taking various examples. Moreover, we will also cover different types of exceptions and errors that are common in a java programming language.
Towards the end of this tutorial, we will also learn about throw and finally keywords and see how they are useful in handling exceptions. In a nutshell, this tutorial is going to have all the details about the java try and catch block method to handle errors and exceptions.
Getting started with try catch Java method
When an error or exception occurs, the java program stops execution further. So in order to continue the execution we have to solve the errors and exceptions by using different java error and exception handling methods. Before going into the details of error and exception handling in java, let us first understand what an error and exception are? In this section, we will define errors and exceptions and their different types in java.
Different Java Error Types
In Java, an error is a subclass of Throwable that tells that something serious problem is existing and a reasonable Java application should not try to catch that error. As these errors are abnormal conditions and should not occur, thus, error and its subclass are referred to as Unchecked Exceptions. Basically, there are two types of java errors which are listed below:
- Compile-time errors: Compile-time errors are the errors resulting from a violation of programming language’s grammar rules, for example writing syntactically incorrect statements. See the example of java compile-time error below:
Run-time errors: Runtime errors occur during runtime or execution of the program because of unexpected situations. Some of the common run-time errors include zero division, invalid input, accessing the array beyond the range and etc. We use the exception handling method of Java to handle such errors. See the example below which gives run-time error when divided by zero.
Different Java Exception Types
Exception in Java is an event that interrupts the execution of program instructions and disturbs the normal flow of program execution. It is an object that wraps an error event information that occurred within a method and it is passed to the runtime system. There are two types of java exceptions which are listed below:
Checked Exceptions: Checked Exceptions are also called compile-time exceptions because they occur at the compile time. If the method contains the code that throws a checked exception, the programmer must provide a mechanism to catch it in the same method. An example of a checked exception can be SQLException .
Unchecked Exceptions: Java Unchecked Exceptions are also called Runtime Exceptions because they occur at runtime. This occurs during the execution of the program. It totally depends upon the developer to catch the runtime or unchecked exceptions. The examples are ArithmeticException , NullPointerException , etc.
Exception handling in Java programming language
Exception handling is a transparent way to handle program errors. It helps us to separate the error-handling code from the normal code and enhances readability. In this section, we will have a close look at the java exception handling method and will see how we can use the java try and catch method along with various examples.
The Syntax of Java try block
The try block in Java contains the statements where there is a chance of exception. A catch block always follows the try block. The simple syntax of java try blocks looks like this;
It is always recommended to use java try block if you think that certain statements in a program can throw an exception. A try block is always followed by a catch block.
The syntax of Java catch block
A catch block is a block where we can handle the exceptions. The catch block must always follow the try block. There can be multiple catch blocks in a try block. The simple syntax looks like this;
So, now the syntax of the java try and catch method looks like this;
Now let us take an example and see how we can handle an error using the java try and catch method.
Example-1: Handle error using try catch Java method
In this section, we will take an example of zero division error and handle it using the java try and catch blocks. See the program below:
Notice that we were able to catch the error and handle it without getting terminated from the program.
Example-2: Handle error using multiple try catch Java blocks
In some cases, we might want to know what kind of error occurs in the try block. In such cases, we can use multiple catch blocks with different possible exceptions. See the example below which uses multiple java try and catch blocks.
Notice that we had specified the type of exception inside the round brackets in the catch block. So, when an error occurs in the try block, then depending on the type of exception the catch block will execute. See the example below which tries to print an element that does not exist in an array.
Notice that when we tried to print the element which does not exist we get an «array index out of range» error and accordingly the catch block was executed.
Example-3: Printing the Java exception
We already have learned how we can handle an exception using the java try and catch block. In some cases, we might also want to print out the error to display to the user. We can do that by printing the error as it is. See the example below:
Notice that we were able to print out the type of exception without knowing it. Now, let us take one more example and print out the exception. See the example below:
Notice that we are able to get the exception type by simply printing it.
More about Java exception handling
Apart from the try and catch block, we can also use java throws and finally keywords to handle java exceptions and errors as well. In this section, we will see how we can use throws and finally blocks in java exception handling by taking various examples.
Throw keyword and Java exception handling
The throws is a keyword used to indicate that this method can throw a specified type of exception. The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions using the throws keyword. With the help of the throws keyword, we can provide information to the caller of the method about the types of exceptions the method might throw. The simple syntax looks like this;
Now let us take an example and see how it actually works. First, let us have a look at the example without using the throws keyword. See the example below:
In the above program, we are getting the compile-time error because there is a chance of an exception if the main thread is going to sleep. Now let us use the throws keyword to handle the above-given error. See the example below:
Finally keyword in Java exception handling
The finally keyword in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception is handled or not. A finally contains all the crucial statements regardless of the exception occurs or not. The simple syntax looks like this;
Now let us use the finally block along with try catch java block. See the example below:
Notice that there was no error and the finally block was executed. Now let us take an example of having an execption with finally keyword. See the example below:
Notice that the finally block was still executed after handling an exception as well. We can conclude that the finally block will be executed with or without having exceptions.
While writing code, we may come across various different kinds of errors and exception and the best way is to handle those exceptions using build in error and exception handling methods. In this tutorial, we learned about try catch java method to handle java exceptions. We first covered different kinds of exceptions that might occur in our program and then solve various examples to handle exceptions using the java try and catch block method.
Moreover, we also learned about the usage of throws and finally keyword in exception handling. All in all, this tutorial is one of the informative tutorials about java try and catch blocks and exception handling.
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
to stay connected and get the latest updates