简体   繁体   English

如何在Java中将Unchecked Exception转换为Checked Exception和Vice Versa

[英]How to convert Unchecked Exception into Checked Exception and Vice Versa in Java

在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. 未检查的异常是RuntimeException子类,未检查的不是。 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 ; 假设您有两个异常类ExceptionAExceptionB and one of them is checked and the other is unchecked. 并且其中一个被选中,另一个未被选中。 You want to convert ExceptionA to ExceptionB . 您想将ExceptionA转换为ExceptionB

Assuming ExceptionB has a constructor like 假设ExceptionB有一个类似的构造函数

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. 将一个异常类的对象包装在另一异常类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM