异常处理

2018-08-10  本文已影响0人  非非非非常胖的大公鸡9527

一个程序在编译时没有错误,但在运行时可能出现各种错误导致程序的退出,这些错误叫做异常。

1.try{.....}catch{......}

异常处理过程:

(1)一旦异常产生,首先会产生一个异常类的实例化对象。

(2)在try语句中对此异常进行捕捉。

(3)产生的异常对象和catch语句中的各个类型进行匹配,如果匹配成功,则执行catch语句中的代码。

很多异常都是类Exception的子类,所以根据多态性,可以让所有的异常都用Exception接收。

2.throws&throw

(1)使用throws声明方法表示此方法不处理异常,而是由调用此方法的地方来处理。

(2)throw是人为的抛出一个异常。

throw和throws的应用例子:

package com.company;
​
class Math{
    public int div(int i,int j) throws Exception {     //方法的异常交给调用方处理
        System.out.println("start counting");
        int temp = 0;
        try {
            temp = i / j;
        } catch (Exception e) {
            throw e;                                   //把异常交给被调用处
        }finally {
            System.out.println("end counting");         //一定执行这个代码
        }
        return temp;
    }
}
​
public class ExceptionTest {
    public static void main(String[] args) {
        Math m = new Math();
        try{
            System.out.println("除法"+m.div(10,0));
        }
        catch (Exception e){
            //System.out.println("异常:"+e);
            e.printStackTrace();
        }
    }
}

3.Exception类和RuntimeException类

区别:

Exception在程序中必须用try...catch...进行处理;

RuntimeException可以不使用try...catch...处理,但如果产生异常,将由JVM处理。

*4.断言

assert boolean表达式

若boolean表达式是ture,则相安无事

若boolean表达式是false,则输出错误信息

上一篇 下一篇

猜你喜欢

热点阅读