Search code examples
javajarexceptionchecked-exceptions

Custom Exception that wraps Multiple Exceptions : Encouraged or Not?


I am coding a Java Library that will be used to access a DB. I am throwing the exceptions to the end-programmer who uses the JAR library to handle it the way he/she wants.

I wrote a custom Exception (provided below) to wrap connection specific exceptions together so the end-programmer will not have to catch all these exceptions in his code. (to make it easy for him)

is this a good practice when it comes to coding Java libraries? By using this the user will only have to catch NConnectionException in his code.

public class NConnectionException extends Exception {
private static final Logger logger = LoggerFactory.getLogger(NConnectionException.class);
public NConnectionException(Exception e) {

    if (e instanceof NullPointerException) {
        logger.error("ERROR IN READING DF");
        e.printStackTrace();
    }

    else if (e instanceof FileNotFoundException) {
        logger.error("FILE NOT FOUND");
        e.printStackTrace();

    } else if (e instanceof ParserConfigurationException)
    {
        logger.error("PARSE CONF ERR");
        e.printStackTrace();

    }
    else if (e instanceof org.xml.sax.SAXException)
    {
        logger.error("SAX ERR");
        e.printStackTrace();

    }
    else if (e instanceof IOException)
    {
        logger.error("IO ERR");
        e.printStackTrace();

    }

}

}


Solution

  • According to this post, wrapping all the exceptions in a single is not good.


    If you want to wrap them then

    As your program will throw only one exception at a time then no need to store list of exceptions in NConnectionException.

    And you can create a single object of exception in NConnectionException class. You can refer this structure.

    And store the thrown exception in that object and throw back newly created object of NConnectionException class. Let the calling program catch NConnectionException exception and take out the stored object and act accordingly.

    Note : Generally we don't handle unchecked exception (like NullPointerException), calling program will take care of it.