Cut abstract exception and repeat on concrete type in Java
There is a situation in my code that looks like this:
Abstract exception
public abstract class AbstractException extends Exception {
...
}
Implemented by three specific exceptions
public class ConcreteException1 extends AbstractException {
// ...
}
public class ConcreteException2 extends AbstractException {
// ...
}
public class ConcreteException3 extends AbstractException {
// ...
}
Method that returns an instance of an abstract exception:
public AbstractException createException()
{
// create an exception that can be one of the 3 concrete class
}
And then in my code, I have a method that handles throwing exceptions:
public void handleThrowing() throws ConcreteException1, ConcreteException2, ConcreteException3
{
//...
throw createException();
}
This code does not compile because "Unhandled AbstractException" exists.
To compile it I had to:
try
{
throw createException();
}
catch (ConcreteException1 | ConcreteException2 | ConcreteException3 ex)
{
throw ex;
}
catch (AbstractException e)
{
throw new IllegalStateException("Exception unknown", e);
}
I'm not very comfortable to maintain, is there a better way to do it?
Thank you for your responses!
+3
source to share