Java – custom exception with multiple exceptions: encouraged or not?

I am writing a Java library that will be used to access the database

I wrote a custom exception (provided below) to wrap connection specific exceptions together so that the programmer doesn't have to catch all these exceptions in his code (for his convenience)

Is this a good practice when writing Java libraries? By using it, the user only needs 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, it's not good to wrap all exceptions together

If you want to package them

Since your program throws only one exception at a time, there is no need to store the exception list in nconnectionexception

You can create a single exception object in the nconnectionexception class You can refer to this structure

Store the thrown exception in the object and return the newly created nconnectionexception class object Let the caller catch the nconnectionexception exception, fetch the stored object and execute the operation accordingly

Note: usually we do not handle unchecked exceptions (such as NullPointerException), and the caller will handle it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>