编程语言
首页 > 编程语言> > java_day09_1

java_day09_1

作者:互联网

 

异常机制

目录

  1. 什么是异常

  2. 异常体系结构

  3. java异常处理机制

  4. 处理异常

  5. 自定义异常

  6. 总结

1 什么是异常

 package com.exception;
 ​
 public class Demo01 {
     public static void main(String[] args) {
         new Demo01().a();//匿名内部类,即新创建的对象没有保存到变量中
 ​
    }
     public void a(){
         b();
    }
     public void b(){
         a();
    }
 }

1.1 简单分类



2 异常体系结构

Throwable

2.1 Error

2.2 Exception

2.3 Error和Exception的区别:



3 Java异常处理机制

 package com.exception;
 ​
 public class Test {
     public static void main(String[] args) {
         int a = 1;
         int b = 0;
 ​
         //假设要处理多个异常:从小到大
         try {//try监控区域
             //System.out.println(a/b);   //不会输出,直接走catch
             new Test().a();
        }catch (ArithmeticException e){  //catch(想要捕获的异常类型!)捕获异常
             System.out.println("程序出现异常,变量b不能为0");
        }finally{   //finally可以不要,一般用来处理善后工作
             System.out.println("finally");
        }
 ​
    }
     public void a(){
         b();
    }
     public void b(){
         a();
    }
 }
 package com.exception;
 ​
 public class Test2 {
     public static void main(String[] args) {
         int a = 1;
         int b = 0;
 ​
         //选中当前要被包裹的代码,ctrl +alt +T
         try {
             System.out.println(a/b);
        } catch (Exception e) {
             e.printStackTrace();   //打印错误的栈信息
        } finally {
        }
 ​
    }
 }
 package com.exception;
 ​
 public class Test2 {
     public static void main(String[] args) {
         try {
             new Test2().test(1,0);
        } catch (ArithmeticException e) {
             e.printStackTrace();
        } finally {
        }
 ​
    }
     //假设这方法中,处理不了这个异常,方法上抛出异常throws(方法上)。
     public void test(int a, int b) throws ArithmeticException{
         if (b == 0){
             throw new ArithmeticException();// 主动抛出异常,throw一般在方法中使用
        }
         System.out.println(a/b);
    }
 }

作用:使用try,catch出现异常后,程序不会停止,还会继续往前走



4 自定义异常

测试程序:

 package com.exception.demo02;
 ​
 public class Test {
     //可能会出现异常的方法
     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(11);
        } catch (MyException e) {
             System.out.println("MyException=>"+e);
        } finally {
        }
    }
 }
 ​

自定义异常类:

 package com.exception.demo02;
 ​
 public class MyException extends Exception{
     //传递数字>10;
     private int detail;
     public MyException(int a){
         this.detail = a;
    }
     //toString:异常的打印信息
     @Override
     public String toString() {
         return "MyException{" + "detail=" + detail + '}';
    }
 }

实际应用中的经验总结

知识补充

1 快捷创建try

标签:day09,java,处理,void,try,catch,异常,public
来源: https://www.cnblogs.com/xinxueqi/p/16089299.html