What it the need of finally block in try-catch | Selenium Forum
M
Posted on 13/08/2016
Coule you please help me to understand....in try catch block, without using finally also we can do whatever we want to do(for example closing DB in your video) by mentioning it after closing catch block ....so what is the need of finally in any case?

Thanks

M
Replied on 15/08/2016

You can attach a finally-clause to a try-catch block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method. Here is how a finally clause looks:


public void openFile(){
FileReader reader = null;
try {
reader = new FileReader("someFile");
int i=0;
while(i != -1){
i = reader.read();
System.out.println((char) i );
}
} catch (IOException e) {
//do something clever with the exception
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
//do something clever with the exception
}
}
System.out.println("--- File End ---");
}
}
No matter whether an exception is thrown or not inside the try or catch block the code inside the finally-block is executed. The example above shows how the file reader is always closed, regardless of the program flow inside the try or catch block.