Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 541
Randhish kumar Avatar asked Mar 25 '26 07:03

Randhish kumar


1 Answers

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);
  }
like image 175
Eran Avatar answered Mar 27 '26 21:03

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!