Try-Catch-Finally In Java | Exception Handling

Mouad Oumous
The Fresh Writes
Published in
9 min readFeb 19, 2023

· Try Blocks
· Catch Blocks
· Finally Blocks
· Putting it all together
· Nested try blocks
· Catch multiple exceptions

Try-Catch-Finally In Java | Exception Handling

Try Blocks

Try blocks are the first part of try/catch blocks. They contain any code that might cause an exception. In Java when we are not certain about the outcome of a statement, we can put those statements inside this try block. A try block can be used in a method or another try block.

The try block is always followed by a catch block, which handles the exception that occurs in the associated try block.

For IOExceptions, put any code that is creating, reading from, writing to, or closing a file inside a try block

Syntax

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following:

try {
code
}
catch and finally blocks . . .

The segment in the example labeled code contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.)

Example

To construct an exception handler for the writeList method from the ListOfNumbers class, enclose the exception-throwing statements of the writeList method within a try block. There is more than one way to do this. You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short.

private List<Integer> list;
private static final int SIZE = 10;

public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entered try statement");
FileWriter f = new FileWriter("OutFile.txt");
out = new PrintWriter(f);
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
}
catch and finally blocks . . .
}

If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it; the next section, The catch Blocks, shows you how.

Try Block Side Notes

  • Alongside code that could trigger an exception, try blocks can (but don’t have to) also contain code that doesn’t cause exceptions.
  • Programs can contain more than one try block. Additionally, it is possible to have one try block inside of another try block.

So if you think while writing a program that certain statements in the program can throw an exception or series of exception, enclosed them in try block and handle that exception smoothly without hampering the program

Catch Blocks

The latter half of a try/catch block is the catch block. While try blocks contain code that causes an exception, catch blocks contain the code that handles an exception.

In Java, the catch block is used to handle the exception which is caught from the try block. The catch block includes the code and it is executed if an exception inside the try block occurs. If the system encounters an exception while executing the statements in a try block, it skips out rest of the statements and transfers the control to the corresponding catch block.

The catch block catches and handles the try block exceptions by declaring the type of exception within the parameter. The declared exception in catch block must be the parent class exception ( i.e., Exception) or the generated exception type. However, the best approach is to declare the generated type of exception.

The catch block will always follow after the try block. Once the control comes out from the try block, there is no way of taking it back in to try block.

Syntax

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.

try {

} catch (ExceptionType name) {

}

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.

Catch Block Arguments

Catch blocks take one argument, the type of exception they are supposed to catch (handle.) These arguments can range from a very specific type of exception to a very general catch-all category of exceptions

Example

The following are two exception handlers for the writeList method:

try {

} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}

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.

Catch Block Contents

The contents of a catch block are what you want to happen when an exception occurs (e.g. when the file being accessed doesn’t exist.) You can either print a message or have code that does something to fix the error (e.g. ask for the file name again.

Catch Block Messages ( Displaying a Description of an Exception )

You can print any message you like inside a catch block.

Using toString()

Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of the exception. You can display this description in a println( ) statement by simply passing the exception as an argument. For example, the catch block in the preceding program can be rewritten like this

catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}

When this version is substituted in the program, and the program is run, each divide-byzero error displays the following message:

Exception: java.lang.ArithmeticException: / by zero

Java also has a few methods that are set up to help handle an exception in a specific way. A couple of these are:

  • getMessage(): returns an error message that’s specific to each type of exception. Pair this with a println statement.
  • printStackTrace() : prints the type of error and where it occurred in the program These methods are especially helpful for debugging and finding the reason for an exception

Catch Block Side Notes

  • Every try block needs at least one catch block.
  • Try blocks can have multiple catch blocks. See the example on the right.
  • Catch blocks must come directly after the try block they are paired with.

Don’t forget to add import statements for your exception types as they are not part of the standard Java library.

Finally Blocks

A finally keyword is used to create a block of code that follows a try block. A finally block of code is always executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of catch block. finally blocks are used to nullify the object references and closing the I/O streams.

Finally Blocks

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.

Syntax

finally {
// cleanup code
}

Example

The following finally block for the writeList method cleans up and then closes the PrintWriter and FileWriter.

finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
if (f != null) {
System.out.println("Closing FileWriter");
f.close();
}
}

Finally Side Notes

  • Finally blocks are an optional addition to try/catch blocks.
  • Finally blocks are used for code that you want to be run no matter what happens exceptionwise with your code.
  • They are the last thing that executes and they will execute every time you run your program.
  • One use of a finally block would be to make sure a file is closed at the end of a program.

Putting it all together

private List<Integer> list;
private static final int SIZE = 10;

public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entered try statement");
FileWriter f = new FileWriter("OutFile.txt");
out = new PrintWriter(f);
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
}
// catch blocks
catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
// finally block
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
if (f != null) {
System.out.println("Closing FileWriter");
f.close();
}
}
}

Nested try blocks

When nested try blocks are used, the inner try block is executed first. Any exception thrown in the inner try block is caught in the corresponding catch block. If a matching catch block is not found, then catch block of the outer try block are inspected. This process continues until all nested try statements are exhausted. If no matching catch block found, program terminates abnormally.

visite nested try-catch block.

Catch multiple exceptions

As you may know in java we can use multiple catch blocks to handle multiple exceptions

Example :

catch (IOException ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
catch (SQLException ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
}

In Java 7, catch block has been improved to handle multiple exceptions in a single catch block.

Example :

catch(IOException | SQLException ex){
logger.error(ex);
throw new MyException(ex.getMessage());
}

visite handle multiple exceptions in java

Happy learning 😃

Join Mouad Oumous Java WhatsApp Group JOIN

Join Mouad Oumous Telegram Channel JOIN

Do support our publication by following it

--

--

Mouad Oumous
The Fresh Writes

I'm a blogger on medium, l'm a java and kotlin developer, also an Android Developer I mastered various topics such as Networking, UI , UX, Animation ...