Java异常机制

时间:2021-03-31 19:24:25   收藏:0   阅读:31

Java异常机制

异常机制处理

package com.exception;

public class Test {
  public static void main(String[] args) {
      int a = 1;
      int b = 0;
      //假设捕获多个异常,从小到大!
      try {//try监控区域
          if(b==0){
              throw new ArithmeticException("数据不能等于0");
          }else{
              System.out.println(a/b);
          }
      } catch (Error e) {//catch捕获异常(捕获异常类型)
          
          System.out.println("有个问题");
      }catch(Throwable e){
          e.printStackTrace();//打印系统错误信息
      } finally{//处理善后工资
          System.out.println("继续输出");
      }

      try {
          new Test().test(a, b);
      } catch (ArithmeticException e) {
          
          e.printStackTrace();
      }finally{//处理善后工资
          System.out.println("继续输出");
      }

     

      //finally可以不写,假设IO,资源的关闭!
  }
  //方法抛出异常用throws
  public void test(int a,int b) throws ArithmeticException {
      System.out.println(a/b);
  }
}

自定义异常

package com.exception;
//自定义异常类,继承exception类
public class MyException extends Exception {
    //传统数字>10
    private int detail;

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

    @Override
    public String toString() {
        return "MyException [detail=" + detail + "]";
    }
    
}
package com.exception;

public class Test {
    public static void main(String[] args) {
        try {
            test(11);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void test(int a) throws MyException {
        if(a>10){
            throw new MyException(a);
        }
    }
}

原文:https://www.cnblogs.com/novice77/p/14602290.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!