How to create a custom exception which wraps three different exceptions like InvalidContextException
, IllegalArgumentException
. For example, let's say there is a method:
public void method() throws IOException, IllegalArgumentException,
InstantiationException, IllegalAccessException {
//Body of the method
}
I want to minimize the number of exceptions after throws keyword by creating a custom exception which handles InstantiationException
and IllegalAccessException
and IllegalArgumentException
together as mentioned below:
public void method() throws IOException, CustomException {
//Body of the method
}
In the spirit of the question as asked:
You would have to catch the various exceptions within your method, and then throw a CustomException
from your catch
block. The ability for an exception to "wrap" around another exception is built in via the Exception
class itself (see the Exception(Throwable cause)
constructor).
public void method() throws IOException, CustomException {
try {
//Body of the method
} catch (IllegalArgumentException | InstantiationException | IllegalAccessException e) {
throw new CustomException(e);
}
}
That said, IllegalArgumentException
is not a checked exception, so you wouldn't have to declare it anyway.
Also worth pointing out, the above is based on you specifying that you want to create a custom exception. Another option is to declare in your throws
clause some type that is a common base class of the various checked exceptions that might actually be thrown. For example, both of the checked exceptions in your list are subclasses of ReflectiveOperationException
, so you could just say
public void method() throws IOException, ReflectiveOperationException {
//Body of the method
}
The trade-off, of course, is that you're not being as informative to those writing code that calls your method, so that may limit the quality of their exception handlers. In the extreme, you could just say throws Thorwable
, but this is pretty poor form.