I am developing an JAR library for database access. I first caught all the exceptions that are found in try blocks and handled them. But later, I thought it would be better since its a library to throw the exception to the end-programmer to catch it and do the handling.
What is the best practice regarding handling exceptions in JAR files?
The following is a sample code from my JAR, and as you can see there are many exceptions thrown. Is that a good practice or is there a way to do this better? (Like defining a new custom exception; if so, how is it done?) Any help regarding this is much appreciated.
public static NConnection getNConnection(String path) throws IOException, ParserConfigurationException, SAXException {
NConfigurations conf = new NConfigurations();
conf.setConfigurationLoc(path);
String dbPath = conf.getDatabasePath();
return createConnection(dbPath);
}
You can do it both ways: you can throw the original exceptions or you can nest them in your own custom exception. It is a design decision.
Usually it makes sense to throw exceptions that are related logically to the code functionality. For ex. if you do I/O operations, you would expect an IOException since this is a natural problem that may arise from the i/o operation.
In your case: it depends what is the NConnection abstraction all about. Maybe it doesn't make sense to expose the IOException if that's implementation specific. You can create your own application-specific exception and wrap the io exception:
try {
// code that throws i/o exception
} catch (IOException ioe) {
throw new NException("Something went wrong", ioe);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With