Java异常处理

基本格式

try{
 被检测的代码
 }catch{
 异常的处理方式
 }finally{
 必须要执行的代码
 }


 finally 无论程序是否异常,代码必须执行, 可用于释放资源

public class FinallyTest {

    public static void main(String[] args) {
        try {
            function(1);
        }catch(Exception ex){
            System.out.println(ex);
        }finally {
            System.out.println("此处代码必须执行");
        }
    }
    public static void function(int a) throws Exception {
        if(a == 0) 
            throw new Exception();
        System.out.println(a);
    }

}

抛出异常

异常关键字:throw,在方法内部抛出异常
throw后必须new异常对象
声明异常关键字:throws
用于在方法声明上,说明此方法可能出现异常,请调用者处理
throws后面写异常类的类名
RuntimeException不需要throws声明

public class ThrowTest {

    public static void main(String[] args)throws Exception {//调用者调用了一个抛出异常的方法,调用者就必须处理
        int[] arr = {};
        int i = getArr(arr);
        System.out.println(i);
    }
    public static int getArr(int[] arr)throws Exception{
        //对方法参数进行判断
        if(arr.length == 0) {
            //throw抛出异常,告诉调用者
            throw new Exception("数组中没有元素");
        }
        int i = arr[arr.length-1];
        return 2*i;
    }    
}

 

posted @ 2019-10-13 22:19  tianqibucuo  阅读(117)  评论(0)    收藏  举报