The try-catch-finally blocks available in the Java exception handling framework are a great way to deal with exceptions. In the previous post, we covered what exceptions are and their types – checked vs unchecked exceptions. Today we’ll enable you to be a pro in using Java try-catch-finally blocks for exception handling.
Before proceeding with this post, I highly recommend you to check out my post on Introduction to Exceptions in Java.
The exception handling in Java makes use of try-catch-finally block which looks structurally 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 :
We put the code which has a possibility to throw an exception inside a try block.catch :
The one or more catch blocks are written to handle different types of exceptions.finally :
finally is mostly used to write clean up code like releasing resources, closing connections etc and is always executed.There are couple of rules you must remember when using try-catch-finally block to handle exceptions.
try
block can have zero or more catch
blocks and at most one (i.e. zero or exactly one) finally
block.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.try, catch
and finally
is a mandate.try, catch
and finally
must appear in the right order or else the code compilation will fail.Once you have understood, the semantic rules of using try, catch and finally for exception handling in Java, let’s have a deeper insight to it.
The above flow-diagram sums up all you need to know regarding try-catch-finally construct in Java.
catch
block.finally
block.finally
block is always executed. The only case when this might not be true could be an abnormal termination of program. For instance, when using System.exit(0)/System.exit(1)
method.finally
block.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 :
In ArithmeticException catch block In finally block After finally block
Now once you have understood how try-catch-finally works, you might be thinking –
‘When no matching
catch
block is found, the exception is thrown to its invoking method . But, then what?’
Yes, you are thinking in the right direction. To answer your question, you 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. I hope you now understand what it means when you see something like this on your console.
Exception in thread "main" java.lang.NullPointerException at com.programmergirl.sampleproject.Book.getName(Book.java:16) at com.programmergirl.sampleproject.Author.getBookNames(Author.java:25) at com.programmergirl.sampleproject.Bootstrap.main(Bootstrap.java:14)
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.
I’ll cover more details on using throws
keyword in one of my upcoming blog posts.Till then, keep learning!