In Java, how to convert Unchecked Exception into Checked Exception and Vice Versa in Java.
4 Answers
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)
3 Comments
Unihedron
Nice one, what if
checkedException is null? What happens?Olaf Kock
when you're "converting" a checkedException, it's probably not null. Otherwise it would be NullpointerException, unchecked. Problem solved ;) (ducks)
Brian Agnew
If you catch an exception, it won't be null. I'm assuming the above would be used in a catch() clause
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.