Java—异常,出错,error和exception处理

2021-03-13

 


 

 

1.try 尝试处理问题

2.catch 捕获

3.finally  无论执不执行最后都会运行的代码

4.throw 和throws 抛出异常

 


 

int a = 1;

int b = 0;

a/b = 1/0 会报错,分母不能等于0

 

 

 *********IDEA中   按【ctrl  +  alt  +  T】可以快捷写好捕捉代码

 


 

异常处理例子:

 

 

 

 


 

情况 1 :错误未知的情况下用 

  ArithmeticException算术运算异常,若改为Throwable 则是捕获所有的异常问题,下面这里是将捕获到该异常的问题命名为 yichang

try和catch是必须的,finally可以不需要,是为了程序出错后做善后工作才写。

catch可以写多个,捕获多种情况,当然如果写了 父级的Throwable,则捕获所有情况了,就不用那么多

 

 

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

   try {
       System.out.println(a/b);
   }catch (
           ArithmeticException yichang
   ){
       System.out.println("程序出现异常");
   }finally {
       System.out.println("必须执行的代码");
   }



    }


}

 


 

情况2 : 预知可能知道会有错误的情况下用

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

  try {
      if (b==0){
          throw new ArithmeticException();
      }
      System.out.println("上面捕获到出错,已抛出异常,所以这里不在执行,直接执行下面的catch代码");
  }catch (Throwable e)
  {
      System.out.println("error");
  }



    }


}

 

posted @ 2021-03-13 22:40  Hello霖  阅读(273)  评论(0)    收藏  举报