• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
Amit Arora
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I am doing a project having a lot of modules. Each module is having its own custom defined exception. Say I have IndexExporter and RequestCreator module having IndexExporterException and RequestCreatorException respectively. These are made to have each module its own specific exception.

The Main module is calling IndexExporter which is calling the RequestCreator. The RequestCreator is having the FileNotFoundException caught using try catch. The exception is wrapped with RequestCreatorEception and thrown. This could be shown in code as:

Request Creator module:

try{
......
}catch(FileNotFoundException e){
throw new RequestCreatorException("File not found, Request Creation Failed", e);
}

This exception is propagated to IndexExporter module where it is again caught and wrapped by IndexExporterException and re-thrown which is then caught by main module.

IndexExporter module:
try{
......
}catch(RequestCreatorException e){
throw new IndexExporterException("Index Exporter Failed", e);
}

Main moudule:

try{
......
}catch(IndexExporterException e){
log.error(e.getMessage(), e);
System.exit(1);
}


If the logging is done in this manner, that produces a complex stack trace. Is this better way to handle the exception?
Should exception be logged as it is caught for the first time as that gives better stacktrace? Then what is the purpose of wrapping the exception?
What is the best way to handle the exception?
Should main catch the exception or it should throw it to JVM?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49843
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try searching the forum. You will find out, unfortunately, that the number of different opinions about exceptions is equal to the number of people asked!

Probably a bad idea to let the Exception propagate as far as the main method; once it gets there, you have lost the rest of your application. If you can handle the Exception nearer to where it is thrown, do so.
Probably a bad idea to log and re-throw at the same time; each Exception will be logged several times and it will make the logging file very difficult to understand.
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is often important to wrap an exception and throw the wrapped exception. But do not do any more wrapping and throwing, it just leads to confusion.

If you are not going to allow an exception to be thrown, then log it. Never allow exceptions to be swallowed without trace.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic