Java中的异常

Java中的异常

 

try(
   //监控区域,把可能出现异常的代码放到这里面
)catch(想要捕获的异常的类型  定义个名字){
   捕获到异常后进行的操作。
}finally{
   不管有没有捕获到异常都去执行的操作,也可以为空。
}
throw:主动抛出异常,一般放在方法里,跟在条件后面,满足条件或不满足条件则自动抛出异常,
throws:向上抛出异常,找到异常但是处理不了,就向上抛出。交给try()catch{}来解决

 

package exception;

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

       try {//try是监控区域,用来存放可能会出现异常的代码。
           System.out.println(a/b);
      } catch (Exception e) {//捕获异常,catch(想要捕获的异常类型 定义的异常名字:存放异常类型)
           System.out.println("程序出现异常,变量b不能等于0");
      } finally {//处理善后工作,不管程序会不会出现异常,finally里的代码都会执行
           System.out.println("善后工作");
      }
       
       
       
       try {
           new Test().Test1(1,0);
      } catch (Exception e) {
           System.out.println("b不能=0");
           e.printStackTrace();//显示异常的类型和具体信息
      }


  }
   public void Test1(int a,int b) throws ArithmeticException{//throws:向上抛出异常

       if (b==0){
           throw new ArithmeticException();//主动抛出异常
      }
  }

}


java中的异常类型
 

 

 

posted @ 2022-10-17 02:35  zhazhawei906  阅读(140)  评论(0)    收藏  举报