嗨,如何将此运行时异常转换为检查异常,此方法必须强制类用户处理方法签名中指定的异常。该异常是未经检查的异常。
public class Exception {
int a, b, c;
void set(String data[]) throws NumberFormatException, ArrayIndexOutOfBoundsException {
a = Integer.parseInt(data[0]);//convert the string into int. eg1.("12" ---> 12) eg2.("df23" ---> fail)
b = Integer.parseInt(data[1]);
c = 0;
}
void divide() throws ArithmeticException {
c = a / b;
}
void disp() {
System.out.println(a + " / " + b + " = " + c);
}
}
最佳答案
只需将其包装到适用于您的上下文的已检查异常
throw new Exception(runtimeException);
我已经使用了Exception
,但您可以使用自己的CustomException
,它扩展了Exception
并将RuntimeException
包装到它。
提示:
还要确保您想要在类似场景中使用检查异常。运行时异常保留在运行时的原因是这种情况无法恢复。因此,请确保您正在包装的运行时异常作为受检查的异常会有所帮助。调用者应该能够从中获得一些值(value)。
其次,正如我在提示中所说,调用者将无法从 ArrayIndexOutOfBoundsException 中恢复,它对调用者没有任何作用。
编辑:
我正在向您展示演示,但我并不赞成这样做。首先,永远不应该抛出ArrayIndexOutOfBoundsException
,您应该注意数组不会超出代码中的索引。
void set(String data[]) throws Exception{
try{
}catch(NumberFormatException ex){
throw new Exception(ex);
}catch(ArrayIndexOutOfBoundsException aiobe){
throw new Exception(aiobe);
}
}
关于java - 如何将这个运行时异常转换为检查异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20991918/