Try Catch Finally in Java Exception handling

In this post we will see the exception handling using the try catch finally in java.

1. Use of Try – Catch Block

A exception in java can be handled using a Try and Catch block.
Lets see a simple example where we have some statements to execute.But one of statement will cause an exception. Now we have to handle this exception and tell the user about the exception.In that case we will need to use the try-catch block. Here the catch block catches the exception and executes the statement inside the catch block and then passes the control back to the next statement if available, else ends the program gracefully.

Output

2. Use of Try – Catch – Finally Block

There are some scenarios where you need to execute some statements regardless of an exception or even if no exception occurs.
For example : You have opened a Database connection and you need to close that connection even if an exception occurs.
Or You are writing/reading a File and you need to close the stream regardless of an exception.
In that scenario we use the finally block.

Some points to remember about finally block ::

  • For a code having try-catch-finally the control flow is

    1. If no exception occurs in try block, then all the statements in try block are executed and then control moves to finally block.
    2. If an exception occurs in try block, then control immediately moves to catch block(remaining statements in try block are not executed), all the statements in catch block are executed and then control moves to finally block.
  • We can write a try block without a catch block. But in that case we need to have a finally block

    In that case the control flow will be

    1. If no exception occurs in try block, then all the statements in try block are executed and then control moves to finally block.
    2. If an exception occurs in try block, then control immediately moves to finally block, all the remaining statements in try block are not executed.

Lets see an example of FileStream and its closing where we use Finally block

Output

What happens if we have return statement in Try or Catch or Finally?

You can find more details on this question here

Return Statement in try catch and finally block

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn