Please consider the following code:
Code Snippet #1
Statement InsertRemoteResultsStmt = null;
Connection connRemote = null;
try {
connRemote = DriverManager.getConnection("//my urls here");
// other stuff here
}
catch(SQLException ex)
{
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
// For Connection #1
InsertRemoteResultsStmt = connRemote.createStatement();
// Rest of the connection code
// For Connection #2 (Will be a new connection)
}
OR
Code Snippet #2:
Statement InsertRemoteResultsStmt = null;
Connection connRemote = null;
try {
connRemote = DriverManager.getConnection("//my urls here");
// other stuff here
}
catch(SQLException ex) // Original catch block
{
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
try{
// For Connection #1 ( Will be using an existing one)
InsertRemoteResultsStmt = connRemote.createStatement();
// Rest of the connection code
// For Connection #2 (Will be a new connection)
}
Catch(SQLException insidecatch)
{
}
break;
}
Que #1 Is Code Snippet #2 a better way of handling exceptions in my case?
For Next Question:
So, I understood that if I have to display something using the exception object, I can do something like following inside the catch block:
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
However, in my case, I am using an existing opened connection inside the catch block as shown above, and I am wondering:
Que #2) Whether the code inside the catch block will start executing automatically as soon as an exception is caught ? I am confused because, in my System.out.println
statements, I am using ex
object to
display all the messages and I am not using this object anywhere in the JDBC connection following it.
Que #3 Is it okay if I use break statement at the end and get out of catch block? Since break is used for loops I believe control will automatically come out of the original catch block?
Clarifications for Que #1:
I am basically comparing two approaches keeping error handling in mind , either of one I am planning to use. In Code Snippet #1 , I have not added any additional try-catch block inside the catch block and vice versa in Code Snippet #2. I am basically using two connections inside catch block. The Connection #1 will be a connectionswhich will be used to insert some records in one database and same with the Connection #2.
Since I have added additional try-catch block inside the catch block, I wanted to know is this approach good to proceed? Just wondering since I have more error handling code here, this approach should be better than theone presented in Code Snippet #1?