My requirement is to send automatic mail whenever the exception arises
public Connection dbConnect(String dbconnectionstring,String userid,String userpassword)
{
Connection connection = null;
System.out.println();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
connection = DriverManager.getConnection(dbconnectionstring,userid,userpassword);
System.out.println("connected to" + dbconnectionstring );
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
now in the other class, if I want to access the content of Exception e (if any exception raises), what should be written in my code to know if any exception raised? and if the exception raised, the content of e should be mailed.
It depends what “other” is. If it is the caller of your
doConnect()method just do not catch the exceptions but throw them and catch in caller method:BTW in java 7 you can catch all exceptions in one block:
} catch(IllegalAccessException | InstantioationException | SqlException e)Alternatively you can wrap specific exception using other exception that can be either checked or unchecked (runtime), e.g.
Now the caller may catch
IllegalStateExceptionand extract its cause.If however you need some kind of asynchronous listener that manages all exceptions you can implement one class like
ExceptionManagerthat is being updated by other classes when exception happens there. TheExceptionManagermay be singleton, so the code will look like this: