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
1 2 3 4 |
File file = new File("data/data.xls"); FileInputStream excelFile = new FileInputStream(file); excelWBook = new XSSFWorkbook(excelFile); excelWSheet = ExcelWBook.getSheet("Screen1"); |
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
1 2 3 4 5 6 7 8 |
try { File myFile = new File("data/data.xls"); FileInputStream ExcelFile = new FileInputStream(myFile); ExcelWBook = new XSSFWorkbook(ExcelFile); ExcelWSheet = ExcelWBook.getSheet(SheetName); } |
Java try-catch block
Syntax :
1 2 3 4 5 6 7 8 |
try { // code } catch { // exception handling code } |
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
1 2 3 4 5 6 7 8 9 10 11 |
try { File myFile = new File("data/data.xls"); FileInputStream ExcelFile = new FileInputStream(myFile); ExcelWBook = new XSSFWorkbook(ExcelFile); ExcelWSheet = ExcelWBook.getSheet(SheetName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } |
Java try-catch-finally block
Syntax :
1 2 3 4 5 6 7 8 9 10 11 12 |
try { // code to execute } catch() { // handle exceptions } finally { // close stream or database connections } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public void loadExcelFile() throws IOException { FileInputStream excelFile = null; XSSFWorkbook excelWBook = null; XSSFSheet excelWSheet = null; try { File myFile = new File("data/data.xls"); excelFile = new FileInputStream(myFile); excelWBook = new XSSFWorkbook(excelFile); excelWSheet = excelWBook.getSheet("Screen1"); excelWBook.close(); excelFile.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (excelWBook != null) { excelWBook.close(); excelFile.close(); } } } |