2

In Java, how to convert Unchecked Exception into Checked Exception and Vice Versa in Java.

Ranga Reddy
  • 2,936
  • 4
  • 29
  • 41

4 Answers4

6

You can't convert. Rather you have to wrap into a new exception of the required type e.g. to convert to unchecked:

throw new RuntimeException(checkedException);

or to checked:

throw new Exception(uncheckedException);

(you may want to choose more meaningful/specific exception types)

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

Unchecked Exceptions are subclasses of RuntimeException, checked ones are not. So to convert one exception you'd have to change its inheritance, then fix the compiler errors because your new checked exception was never declared or caught.

Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
0

There is no way you can convert them. They are for different purposes. Caller needs to handle checked exceptions, while unchecked or runtime exceptions aren't usually taken care explicitly.

Swapnil
  • 8,201
  • 4
  • 38
  • 57
0

Let's say you've got two exception classes ExceptionA and ExceptionB; and one of them is checked and the other is unchecked. You want to convert ExceptionA to ExceptionB.

Assuming ExceptionB has a constructor like

public ExceptionB(Exception e) {
    super(e);
}

you can do something like

catch (ExceptionA e) {
    throw new ExceptionB(e);
}

to wrap objects of one exception class in the other.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110