Day8-9 捕获抛出异常

捕获和抛出异常

异常处理的五个关键字

try、catch、finally、throw、throws

 package com.exception;
 ​
 public class test {
     public static void main(String[] args) {
         int a=1;
         int b=0;
         try{//try监控区域
             if (b==0){//throw
                 throw new ArithmeticException();//主动抛出异常,一般在方法中使用
             }
             System.out.println(a/b);
         }catch (ArithmeticException e){//catch(想要捕获的异常类型) 捕获异常
             System.out.println("程序出现异常");
         }finally {//处理善后工作
             System.out.println("finally");
         }
         //finally可以不要,IO流资源关闭放在finally
     }
 }

 

 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) {
             throw new RuntimeException(e);//打印错误的栈信息
         } finally {
         }
     }
 ​
 }

 

 
posted @ 2022-11-18 16:40  actadams68  阅读(49)  评论(0)    收藏  举报