异常

发布时间 2023-03-23 14:14:56作者: 霍叔

异常

异常体系结构

  • Java把异常当做一个对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类。

  • 在Java API中已经定义了许多异常类,这些异常类分为两大类,错误的Error和异常Exception

  •  

     

            int a=10;
    int b=0;

    //idea快捷键选中代码Ctrl+Alt+T

    try {//try监控区域
    System.out.println(a/b);
    } catch (Error err) {//系统错误
    System.out.println("Error");
    } catch (Exception exce) {//系统异常(ArithmeticException)
    System.out.println("Exception");
    } catch (Throwable th) {//捕捉系统全部异常
    System.out.println("Throwable");
    } finally{//处理善后工作用于资源关闭
    System.out.println("finally");
    }

    对应输出:

    Exception
    finally

    捕获异常

    public class demo3 {
       public static void main(String[] args) {

           try {
               new demo3().mm(10,0);
          } catch (ArithmeticException e) {
               e.printStackTrace();
          } finally {
               
          }

      }

       public void mm(int a, int b)throws ArithmeticException{
           if (b==0){
               throw new ArithmeticException();
          }
      }
    }