java - 如何将这个运行时异常转换为检查异常?

标签 java exception

嗨,如何将此运行时异常转换为检查异常,此方法必须强制类用户处理方法签名中指定的异常。该异常是未经检查的异常。

 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/

相关文章:

java - 如何避免 null 检查 - OOP

java - 空指针协助。

android - 如何在 ionic 应用程序(cordova/phonegap)中获得完整的异常堆栈跟踪而不是一行?

java - 捕获多个异常的处理程序?

java - batik 将 SVG 转换为 JPEG

java - Android : How to get just two digit after the point in decimal value ? 不想截断值

java - 内存不足错误: unable to create new native thread while using Executor

exception - 更改 Lazarus 中的异常消息

python - 为什么我的代码打开另一个文件并处理错误异常?

php - CakePHP 3 : Exception not Found