-1

Consider the following Java snippets:

try{
   //Some code to tryout
}
catch(Exception e){
   //Catch if there is an exception
}
finally{
   //SNIPPET1 that is always executed
}

The above snippet is essentially equal to

try{
   //Some code to tryout
}
catch(Exception e){
   //Catch if there is an exception
}
//SNIPPET1 that is always executed

I know that finally block is usually used to close network connections, file streams etc. I do not see a strong motivation in introducing this keyword into the language because one can happily program without using it as well.

Can you please explain the rationale behind introducing this keyword?

router
  • 582
  • 5
  • 16
  • 4
    Think about this: What happens if an exception is thrown in the `catch` block? (In that case there's a difference in behaviour between the two snippets you posted). – Jesper Jun 16 '17 at 11:01
  • 1
    This block allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.It is also a key tool for preventing resource leaks – Akshay Jun 16 '17 at 11:02
  • You can also refer java docs https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html – Akshay Jun 16 '17 at 11:04
  • Sorry for the duplication. Closing the question... Edit: Apparently I couldn't :P – router Jun 16 '17 at 11:21

1 Answers1

4
try {
    // statement 1
} catch (Exception e) {
    // statement 2
}
// statement 3

statement 3 won't be executed if statement 2 throws an exception

Mykola Yashchenko
  • 5,103
  • 3
  • 39
  • 48