How to convert / wrap Unchecked Exceptions into Checked Exceptions in Java?

1k views Asked by At

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.

2

There are 2 answers

1
Eran On BEST ANSWER

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);
  }
0
Peter Lawrey On

You can wrap an unchecked exception with a checked exception

try {
    // do something
} catch (RuntimeException re) {
    throw new CheckedException("Some message", re);
}