异常

1、try监控区域 , catch捕获异常 , finally处理善后工作 , throw和throws抛出异常。

2、catch可以写多个,最大的异常必须写在最后面,从小到大。

3、try和catch必须使用,finally可以不使用。

4、快捷键: Ctrl + alt + t

5、在方法上是throws 抛出异常, 在方法里是throw。

 

例1:

1 public class Demo1 {
2     public static void main(String[] args) {
3         int a = 1;
4         int b = 0;
5         System.out.println(a/b);
6     }
7 }

这个代码会出现异常!

 

 

 我们通过编译后的异常写入代码中

 1 public class Demo1 {
 2     public static void main(String[] args) {
 3         int a = 1;
 4         int b = 0;
 5 
 6         //try监控区域
 7         //try 和 catch必须使用, finally可以不使用。
 8         try {
 9             System.out.println(a/b);
10             //catch 捕获异常,  catch(想要捕获的异常类型)
11             //catch 可以写多个, 最大的异常必须写在最后面,从小到大
12         }catch(ArithmeticException e){
13             System.out.println("程序出现异常,变量b不能为0");
14             //处理善后工作
15         }finally{
16             System.out.println("finally");
17         }
18     }
19 }

编译后结果

 

 

 

例2:

写多个catch,从小到大,不能乱写不然要报错!

 1 public class Demo1 {
 2     public static void main(String[] args) {
 3         int a = 1;
 4         int b = 0;
 5 
 6         //try监控区域
 7         //try 和 catch必须使用, finally可以不使用。
 8         try {
 9             System.out.println(a/b);
10             //catch 捕获异常,  catch(想要捕获的异常类型)
11             //catch 可以写多个, 最大的异常必须写在最后面,从小到大
12         }catch(Error e){
13             System.out.println("Error");
14         }
15         catch(Exception e){
16             System.out.println("Exception");
17             //处理善后工作
18         }catch (Throwable e){
19             System.out.println("Throwable");
20         }
21         finally{
22             System.out.println("finally");
23         }
24     }
25 }

 

posted @ 2022-03-11 16:55  小王同学学编程  阅读(25)  评论(0)    收藏  举报
levels of contents