top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Exception Handling in Java – try, catch and finally


Introduction:

The try-catch-finally blocks available in the Java exception handling framework are a great way to deal with exceptions.


The exception handling in Java makes use of try-catch-finally block which looks somewhat like the one mentioned below.


try{

//code which might throw an exception

......

......

}catch(ExceptionType1 type1){

//code to handle exception of type -ExceptionType1

.....

}

catch(ExceptionType2 type2){

//code to handle exception of type -ExceptionType2

.....

}

...

//some more optional catch blocks

finally{

//code that has to be executed in both success and failure scenarios

}


Try Block In Java

Whenever we are writing a program there could be a code that we suspect might throw an exception. For example, we might suspect that there might be a “division by zero” operation in the code that will throw an exception.

This code that might raise an exception is enclosed in a block with the keyword “try”. So the try block contains the code or set of statements that can raise an exception.

When an exception occurs in a try block at a particular statement, then the control comes out and the program terminates abruptly. To prevent this abrupt termination of the program, we should “handle” this exception. This handling is done using the “catch” keyword. So a try block always has a catch block following it.


Catch Block In Java

We use a catch block to handle exceptions. This is the block with the “catch” keyword. The catch block follows the try block.

Whenever an exception occurs in the try block, then the code in the catch block that corresponds to the exception is executed.

Generally, the declared exception must be the parent class of all exceptions, i.e. Exception. But if there is more than one exception, we can also write specific exception types or generated exceptions.


Finally Block In Java

We need a separate block that contains a code that executes irrespective of whether an exception occurs or not. Java provides a “finally” block that contains this piece of code.

Hence a finally block in Java can contain critical statements that are to be executed in the program. The execution of these statements should be carried out even when an exception occurs or not.

Therefore, we will put code like closing connections, stream objects, etc. or any cleanup code in the finally block so that they can be executed even if an exception occurs.

finally block is optional.


There are couple of rules you must remember when using try-catch-finally block to handle exceptions.


  1. A try block can have zero or more catch blocks and at most one (i.e. zero or exactly one) finally block.

  2. A try block must either be followed by at least one catch block or a finally block. try block with no catch as well as no finally clause will fail to compile.

  3. The block notations(i.e. using curly braces – ‘{ } ‘) for all the three clauses – try, catch and finally is a mandate.

  4. try, catch and finally must appear in the right order or else the code compilation will fail.

How it works ?


  1. When an exception occurs, JVM creates and pass the exception object to the first matching catch block.

  2. Once the code within the first matching catch block is executed, if found, the control flows to the finally block.

  3. finally block is always executed. The only case when this might not be true could be an abnormal termination of program.

  4. For instance, when using System.exit(0)/System.exit(1) method.

  5. If the exception was handled by one of the catch blocks, the code flows naturally to the next line in the method after finally block.

  6. If not, the exception object is thrown to the invoking method for it to handle the exception.

Sample Usage :

package Practice; public class TryCatchFinally { public static void main(String[] args) { try{ int a=10/0; }catch(ArithmeticException ae){ System.out.println("In ArithmeticException catch block"); }catch(Exception ae){ System.out.println("In Exception catch block"); }finally{ System.out.println("In finally block"); } System.out.println("After finally block"); } }


The above code will produce the following output :




Exception Propagation :

Now once you have understood how try-catch-finally works, We will have a question-


When no matching catch block is found, the exception is thrown to its invoking method . But, then what?


To answer the question, we need to understand the exception propagation principle which says :


The exception will be propagated to its invoking method, if not handled within the method in which it is thrown .

This invoking method which is now on the top of call stack will either handle the exception using try-catch-finally or else it will be again propagated to its invoking method. This propagation will continue down the stack trace till either the exception is handled or we reach the main() method.

If it is not handled even within the main() method, it will be propagated to the JVM which will handle it by invoking it’s default exception handler.

The JVM by default handles the exception by printing the stack trace on the console like this.

Exception in thread "main" java.lang.ArithmeticException: / by zero at Practice.TryCatchFinally.main(TryCatchFinally.java:8)


Conclusion :


Today, we learnt exception handling in Java using try-catch-finally construct and looked at various rules around its usage.

We also looked at the exception propagation principle and how exception object propagates down the stack trace, if not handled.

However, it is important to highlight that only the unchecked exceptions make use of the exception propagation principle.

For the checked exceptions, we must declare the exception in the method definition using throws keyword or else code compilation fails.


29 views0 comments

Recent Posts

See All
bottom of page