搜索

day17 - 异常


发布时间: 2022-11-24 18:42:09    浏览次数:68 次

异常

在软件程序运行过程中,遇到异常等问题,进行合适的处理,不至于让程序崩溃。

异常发生在程序运行期间,影响了程序的正常流程。

异常和error的区别

  1. error一般是致命性的错误,是无法处理和控制的

  2. exception可以被程序处理的

       
 1  int a =1;
 2          int b =0;
 3          try {//try 监控区域:
 4              System.out.println(a/b);
 5          }catch (Error e){//捕获异常 catch(想要捕获的异常类型)
 6              //最高级的是Throwable
 7              System.out.println("error");
 8          }catch (Exception m){
 9              System.out.println("exception");
10          }catch (Throwable t){
11              System.out.println("throwable");
12          } finally {//处理善后工作
13              System.out.println("finally");
14          }
15          //finally 可以不要,在IO,资源的关闭工作使用
16  public class Test {
17      public static void main(String[] args) {
18          try {
19              new Test().test(1,0);
20          } catch (ArithmeticException e) {
21              e.printStackTrace();
22          }
23 24      }
25      //假设在这个方法中处理不了这个异常,则在方法上抛出异常(throws)
26      public void test(int a,int b) throws ArithmeticException{
27          if (b==0){
28              throw new ArithmeticException();//主动抛出异常,一般在方法中使用
29          }
30          System.out.println(a/b);
31 32      }
33  }
34  public class Test2 {
35      public static void main(String[] args) {
36          int a =1;
37          int b =0;
38          //快捷键: CTRL +ALT +T
39          try {
40 41              if (b == 0){// 主动抛出异常 throw throws
42                  throw new ArithmeticException();
43 44              }
45              System.out.println(a/b);
46          } catch (Exception e) {
47 48          } finally {
49          }
50      }
51  }

 

自定义异常

自定义异常:

 1  public class MyException extends Exception{
 2      //传递数字>10抛出异常
 3      private int detail;
 4  5      public MyException(int a) {
 6          this.detail=a;
 7      }
 8      //toString:打印异常的信息
 9      @Override
10      public String toString() {
11          return "MyException{" +
12                  "detail=" + detail +
13                  '}';
14      }
15  }

 

使用异常

 1  public class Test {
 2      //可能会存在异常的方法
 3      static void test(int a) throws MyException {
 4          System.out.println("num is : "+a);
 5          if(a>10){
 6              throw new MyException(a);//抛出
 7          }
 8          System.out.println("okok");
 9 10      }
11 12      public static void main(String[] args) {
13          try {
14              test(12);
15          } catch (MyException e) {
16              System.out.println("MyException=>"+e);
17          }
18 19      }
20  }

 

 
免责声明 day17 - 异常,资源类别:文本, 浏览次数:68 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 06:42:09。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/GUGUZIZI/p/16807644.html