2

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

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Nice one, what if checkedException is null? What happens?
when you're "converting" a checkedException, it's probably not null. Otherwise it would be NullpointerException, unchecked. Problem solved ;) (ducks)
If you catch an exception, it won't be null. I'm assuming the above would be used in a catch() clause
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.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.