How can I convert or wrap thrown exceptions to checked exceptions in Java?
Can Unchecked Exceptions be converted to Checked Exceptions in Java? If so, please suggest ways to convert or move the thrown exception into a checked exception.
+3
Randhish kumar
source
to share
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
Eran
source
to share
You can wrap a checked exception with a checked exception
try {
// do something
} catch (RuntimeException re) {
throw new CheckedException("Some message", re);
}
+2
Peter lawrey
source
to share