Java-07-异常处理机制

Java 异常处理机制

异常处理的五个关键字

try,catch,finally,throw,throws

1.抛出异常

public class autoCapture {
    
    
    public static void main(String[] args) {
    
    
        int a = 1;
        int b = 0;
        //ctrl+alt+t
        new autoCapture().test(a,b);

        //如果不适用try catch 程序会停止,用了程序仍会正常的执行
        try {
    
    
            System.out.println(a/b);
        } catch (Exception e) {
    
    
//            System.exit(1);//手动结束
            e.printStackTrace();//打印错误的栈信息

        }

    }
    
    //假设该方法中,处理不了该异常.可以在方法上抛出异常 throws关键字
    public void test(int a ,int b) throws ArithmeticException{
    
    
        System.out.println(a/b);
//        if (b==0){
    
    
//            throw new ArithmeticException();//主动抛出异常,一般在方法中使用
//        }
    }
}

    

2.捕获异常

	public class test {
    
    
    public static void main(String[] args) {
    
    
        int a = 1;
        int b = 0;

        try {
    
    //try监控区域
            System.out.println(a/b);
        }catch (Error error){
    
    //catch(想要捕获的异常类型[Throwable\Error\Exception]) 捕获异常,catch可以写多层(小->大)
            System.out.println("error:"+error);
        }catch (Exception e) {
    
    
            System.out.println("Exception:" + e);
        }catch(Throwable t){
    
    
            System.out.println("Throwable"+t);
        }
        finally {
    
    //程序无论是否出现异常,都将执行finally代码块,处理善后事宜
            System.out.println("finally");
        }

        //finally 非必须,但IO流或涉及资源,无论如何都要释放,则放在fianlly

    }
}

3.自定义异常

//继承Exception
public class MyException extends Exception {
    
    
    //传递数字>10
    private int detail;

    public MyException(int detail) {
    
    
        this.detail = detail;
    }

    //toString:异常的打印信息

    @Override
    public String toString() {
    
    
        return "My Exception {"+detail+"}";
    }
}

测试我的异常

public class TestMyException {
    
    
    //可能会存在异常的方法


    static void test(int a) throws MyException{
    
    
        System.out.println("传递的参数为"+a);
        if(a>10){
    
    
            throw new MyException(a);//抛出
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
    
    
        try {
    
    
            test(12);
        } catch (MyException e) {
    
    
            System.out.println(e);
        }
    }
}

image-20210305144533876

4.有关异常的总结

异常总结
    1.处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
    2.在多重catch块后面,可以加一个catch(Exception)来处理可能被遗漏的异常
    3.对于不确定的代码,也可以加上try-catch,处理潜在的异常
    4.尽量去处理异常,不要总是简单的调用printStackTrace()去打印输出
    5.尽量添加finally语句块去释放占用的资源
可能被遗漏的异常
    3.对于不确定的代码,也可以加上try-catch,处理潜在的异常
    4.尽量去处理异常,不要总是简单的调用printStackTrace()去打印输出
    5.尽量添加finally语句块去释放占用的资源

猜你喜欢

转载自blog.csdn.net/baidu_41656912/article/details/114396646