Home > Software engineering >  Wrapping exceptions in java, best way
Wrapping exceptions in java, best way

Time:11-07

So im reading the below and i understand why you would do it.. https://jenkov.com/tutorials/java-exception-handling/exception-wrapping.html

example :

   try{
        dao.readPerson();
    } catch (SQLException sqlException) {
        throw new MyException("error text", sqlException);
    }

So what if i want to isolate all external exceptions inside the dao layer only, and only use my exceptions. so in the above example i dont want to send SQLEXception inside the constructor, would doing the below be enough. Would it contain enough information :

        throw new MyException("error text", sqlException);

or maybe my constructor should be the following instead

public MyException(String text,Exception ex)

CodePudding user response:

You can inherit your exception from Exception like

MyException extends Exception {

}

and then use try catch like :

try {
    dao.readPerson();
} catch (MyException ex) {
    // handle Exception
}

by doing this you can do whatever you want in your class and i think its cleaner than other ways. It will trigger automatically so you dont need to raise an exception.

If you want to catch SQL Exceptions only you can inherit MyException from SqlException so it will only trigger when SqlException happens

CodePudding user response:

I understand that you worry about the catching part of your code knowing about the wrapped exception. In "not knowing" there are different layers.

Level 1: Nothing obligates the catching class to get the cause and therefor explicitly knowing about the SQLException. They just catch the MyException and don't care what's wrapped in it. Usually that's enough.

Level 2. Another level of not knowing is restricting the catching class to even have access to the wrapped exception. In that case why wrap it at all? Just catch the SQLException in your DAO layer and throw MyException without wrapping the original exception in it.

About wrapping the causing Exception instead of the original one. You could do that but you might lose valuable information so 99% of the time it's not recommended. There are some corner cases where I've done it though. Let's say you throwing code runs asynchronously through ExecutorService. Then if an exception is thrown it's wrapped to ExecutionException, but as a caller I might not be interested that the code ran asynchronously so I catch the ExecutionException, get it's cause (the actual exception that happened) and wrap that to my custom exception.

  •  Tags:  
  • java
  • Related