This morning I was going through an article try-catch-finally (TCF) in Java.
Suddenly got some weird thoughts.
Plugged myself to Eclipse to dive into the right answers. Here are few bullets:
1. Can try exist all alone ( without catch, without finally) ?
ANS: try block {1} i.e 1 time
catch block * i.e 0 or N times
finally block ? i.e 0 or 1 time
2. Can I put just try block in an “if” condition leaving catch block independent?
if(alive){ try{ //dive into pacific ocean once more { } // end of if catch(Exception e) { // Reported dead before entering to pacific }
ANS: No. You cant associate catch without if.
3. I want to write the below JDBC scenario in below manner:
try block -> Establish a connection to the database & submit a query to the MySQL database for execution
catch block -> If connection failure or query failure happens, will give a message to the end user.
finally block -> close the database connection at any cost
Not a big deal, my code is ready. Here I go………
public class TtryCatchFinallyDemo { public static void main(String[] args) { Connection con = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "password"); stmt = con.createStatement(); rs = stmt.executeQuery("Select * FROM user"); while (rs.next()) { System.out.println(rs.getString("User2")); //Mistaken purposely- User2 instead "User" // PlaceHolder_00 } con.close(); // PlaceHolder_01 } catch (Exception e) { System.out.println("Exception Occurred :- " + e.getMessage()); // PlaceHolder_02 }finally{ con.close; // PlaceHolder_03 } } } }
Looks absolutely fine. Right?
No. It has error.
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Unhandled exception type SQLException
Assume the error happens at PlaceHolder_00, control will move to the exception block and then finally block.
Writing con.close() at PlaceHolder_01 will not close the database connection. Thus I need to close it at finally block at PlaceHolder_03.
But will it serve my purpose?
Thus the correct way of doing it would be
Modify the above code to
finally{ try{ System.out.println(con.isClosed()); // false con.close(); System.out.println(con.isClosed()); // true con = null; }catch(Exception e){// PlaceHolder_03 System.out.println("Exception occurred!"); } }
But again re-writing try catch withing finally wont be a good idea.
Hopefully setting the con to null will solve everything.
finally{ con = null; }