3

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.

Eran
  • 387,369
  • 54
  • 702
  • 768

2 Answers2

2

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);
  }
Eran
  • 387,369
  • 54
  • 702
  • 768
2

You can wrap an unchecked exception with a checked exception

try {
    // do something
} catch (RuntimeException re) {
    throw new CheckedException("Some message", re);
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130