Can Unchecked Exceptions be converted into Checked Exceptions in Java? If yes, please suggest ways to convert/wrap an Unchecked Exception into a Checked Exception.
Yes. You can catch the unchecked exception and throw a checked 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);
}