自定义抛出异常会导致意外编译错误

时间:2014-04-21 17:31:36

标签: java exception throw divide-by-zero throws

我想在下面的代码中创建一个自定义异常来处理可能的除零,但是编译器声明我声明的异常是未报告的。 很抱歉这类问题,但我是java和面向对象编程的初学者。

public class Exception_Tester {
    public static void main(String args[]) { 
        Exception_Tester et = new Exception_Tester(); 
        int x1; 
        int x2; 
        x1 = 5; 
        x2 = 0;
        et.printResults(x1, x2);       
       } 
    void printResults(int a, int b) throws ArithmeticException { 
        System.out.println("Add: "+(a+b)); 
        System.out.println("Sub: "+(a-b)); 
        System.out.println("Mul: "+(a*b)); 
        if(b != 0)
            System.out.println("Div: "+(a/b));
        else{ 
        Exception myException = new ArithmeticException("You can't divide by zero!");
        throw myException;
        } 
    }
}


编译器错误:未报告的异常java.lang.Exception;必须被抓住或宣布被抛出

1 个答案:

答案 0 :(得分:1)

问题是你在方法中抛出了未声明的Exception

Exception myException = new ArithmeticException("You can't divide by zero!");
throw myException; //here you throw Exception

您可以通过以下任何方式解决此问题:

  • 声明您的方法抛出Exception

    void printResults(int a, int b) throws Exception {
        //...
    }
    
  • 按原样抛出新的ArithmeticException

    //Exception myException = new ArithmeticException("You can't divide by zero!");
    throw new ArithmeticException("You can't divide by zero!");
    

请注意,ArithmeticExceptionRuntimeException延伸,因此您的方法无需声明它。所以,你的代码可能是这样的:

void printResults(int a, int b) { 
    System.out.println("Add: "+(a+b)); 
    System.out.println("Sub: "+(a-b)); 
    System.out.println("Mul: "+(a*b)); 
    if(b != 0) {
        System.out.println("Div: "+(a/b));
    } else {
        throw new ArithmeticException("You can't divide by zero!");
    }
}