Dealing with inaccessible exception types

I'm working with a third-party library that has some very specific exception types for different scenarios. I'd like to use them like this (a somewhat simplified version):

try
{...}
catch (IllegalFooOperationException e)
{
    //handle an illegal foo
}
catch (InvalidBarValueException e)
{
    //handles very differently from the illegal foo.
}

Unfortunately, IllegalFooOperationException and InvalidBarValueException are not public classes: they are package-scoped. They inherit from a much more generic public GenericThirdPartyAPIException class.

Right now, this sort-of works:

catch (GenericThirdPartyAPIException e)
{
    String rootExceptionTypeName = e.getClass().getName();
    if (rootExceptionTypeName.equals("someAPI.IllegalFooOperationException"))
    {
        //handle illegal foo
    }
    else if (rootExceptionTypeName.equals("someAPI.InvalidBarValueException"))
    {
        ...
    }
}

But this just doesn't feel right. One potential problem is that if the packages or class names change in the future in this library, this code won't be able to find the right exception class at runtime. I don't like relying on figuring out an object's class at runtime if I don't have to.

I also thought about trying to parse the exception message directly, but there some of the exceptions I'm interested in (not all are shown here) might have the same message, but be of a different type.

Is there a better way to handle this situation?

Upvotes: 2

Views: 319

Answers (1)

Gaetano Piazzolla
Gaetano Piazzolla

Reputation: 1547

In the initialization you could execute a method that for sure throws IllegalFooOperationException and save the class of the exception in a variable. Do the same thing for the other exceptions, and you shoud have all the exception classes.

I know that this is not a good practice (as the package protected exceptions are are as well) but you will be able to find the right exception class at runtime.

Upvotes: 2

Related Questions