Java try-catch block

Posted in Exception Handling By Raj On December 26, 2017

 

In my previous article, I have explained about exception handling, in this article, I am going to explain to you how to use try-catch block in Java

Let me take a simple example, the code which you see below will  throw FileNotFoundException if there is no .xls file exists in the specified folder and it will break normal flow if you directly run the below code 

To avoid the this, we need to keep the code in the try block so that whenever an error occurs it will handle it

Java try block

A try block encloses with set of statements which might throw an exception, the code which is in the try block executes until it throws exception or all the statements executes successfully

Java try-catch block

Syntax :

When an exception is thrown in try block the JRE immediately look for catch block to handle it, if you don’t add catch block then it will throw checked exception

Java try-catch-finally block

Syntax :

The final block is used to close the streams or to close database connections etc…, in the below real-time example, we are using FileInputStream class to read the excel file which is an IO operation, so we must close it

The final block always executes whether error occurred or not, so we must use java final block to close our FileInputStream object

You can close stream object in the try block but what happens if some error occurs, the remaining code will not execute and finally end up will with memory leakage issue