DESKTOP-7HC873M_20200904-李宗宝

问题

在编译阶段中 受编译器检查 ,如果程序中存在没有处理的受检查异常,则编译器拒绝编译

对于 受检查异常来说 ,源代码中 要么通过 try...catch语句块来捕获异常,要么为相应的方法添加 throws 声明,否则编译器拒绝编译

public int divide( int dividend , int divisor ) throws Throwable {
        if( divisor == 0 ) {
            Exception ex = new Exception( "除数不能为零" ) ;
            // 对于抛出的受检查异常(checked-exception)来说
            // 必须显式通过try...catch语句处理或者为当前方法显式声明throws语句
            throw ex ; 
        }
        return dividend / divisor ;
    }

对于 运行时异常 来说,可以使用 try...catch...语句块来处理,也可以不处理,编译时编译器并不会做出检查

通过 printStackTrace方法可以打印异常的堆栈信息 ( printStackTrace 由 Throwable 类所定义)

public int divide( int dividend , int divisor ) {
        // ArithmeticException是RuntimeException的子类,属于运行时异常
        return dividend / divisor ; // 可能发生ArithmeticException
    }
    
    public Integer modular( int dividend , int divisor ) {
        try {
            return dividend % divisor ;
        } catch (ArithmeticException ae) {
            ae.printStackTrace();
            return null ;
        }
    }

心得

今天天气真不错