How can I convert or wrap thrown exceptions to checked exceptions in Java?
2 answers
Yes. You can catch an unchecked exception and throw the thrown exception.
Example:
public void setID (String id)
throws SomeException
{
if (id==null)
throw new SomeException();
try {
setID (Integer.valueOf (id));
}
catch (NumberFormatException intEx) { // catch unchecked exception
throw new SomeException(id, intEx); // throw checked exception
}
}
Then, in the constructor of the checked exception, you call initCause
with the passed exception:
public SomeException (String id, Throwable reason)
{
this.id = id;
initCause (reason);
}
+2
source to share