在Java中,如何在Java中将Unchecked Exception转换为Checked Exception和Vice Versa。
You can't convert. Rather you have to wrap into a new exception of the required type eg 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)
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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.