编程语言
首页 > 编程语言> > Java异常

Java异常

作者:互联网

Exception

异常处理框架
在这里插入图片描述

异常处理机制

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

        try { //try监控区域
            System.out.println(a / b);
        } catch (ArithmeticException e){ //catch捕获区域  
            // 括号内为捕获异常的属性 最高为Throwable
            System.out.println("程序出现异常");   
        }finally{       //无论是否出现异常,都执行
            System.out.println("finnaly");
        }
    }
}

command+option+t 可以自动生成try/catch

e.printStackTrace(); 打印错误栈信息

主动抛出异常 throw/throws

方法抛出异常,一般处理不了

if(b==0){
  throw  new ArithmeticException(); //主动抛出异常,一般在方法中使用
    }

方法上抛出异常

public void test(int a, int b) throws ArithmeticException{
...
}

自定义异常(少用)

继承exception

 public class MyException extends Exception{
...
	}

标签:Java,int,抛出,ArithmeticException,System,异常,public
来源: https://blog.csdn.net/weixin_47903213/article/details/121291734