1

I know, that finally block is always executed even if exception occurs.

It doesnt execute if we use System.exit(0) in try or catch block;

It is used for releasing resources.

But I have question, the statements after catch block will anyways execute even if those are written without finally, right?

Please explain me.

See the following code snippets -

public static void main(String[] args) throws SQLException {

    Connection con=null;
    try {
        String url ="someURL";
        String user ="someUserName";
        String password ="somePassword";

        con=DriverManager.getConnection(url, user, password);
        .
        .
        .
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        if(con!=null) {
            con.close();
        }
    }

}

and

public static void main(String[] args) throws SQLException {

    Connection con=null;
    try {
        String url ="someURL";
        String user ="someUserName";
        String password ="somePassword";

        con=DriverManager.getConnection(url, user, password);
        .
        .
        .
    }catch(Exception e) {
        e.printStackTrace();
    } 

   if(con!=null) {
     con.close();
   }


}

So my con.close(); will execute anyways, then why I need finally?

Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55

2 Answers2

1

In this particular case I would say that this indeed is somehow identical, but have you considered a try with resource so that con is closed automatically? this would be the cleanest way I can think of.

Of course if something not as Exception is thrown (Throwable for example), then your connection would not be closed without a finally ...

Eugene
  • 117,005
  • 15
  • 201
  • 306
0

Usually catching all exceptions with a catch block is not the best practice. In such a case, if any thing that is not caught is thrown, finally will be helpful. And, your 2nd code snippet will not work.

Gimhani
  • 1,318
  • 13
  • 23