java处理异常的机制关键字为throw和throws

在异常处理的过程中,throws和throw的区别是?

throws:是在方法上对一个方法进行声明,而不进行处理,而是向上传,谁调用谁处理.

throw:是在具体的抛出一个异常类型.

throws的栗子:

throws的话,就是这个方法有可能会产生异常,而我只是将它声明出去,我自己不处理,如果有人调用的时候,可以知道,这个方法,有可能会抛出异常,我要是调用的话,我就得处理,或者接着throws.

格式是:方法名(参数)throws 异常类1,异常类2,.....
 1 class Math{
 2       public int div(int i,int j) throws Exception{
 3           int t=i/j;
 4           return t;
 5       }
 6  }
 7 
 8 public class ThrowsDemo {
 9       public static void main(String args[]) throws     Exception{
10           Math m=new Math();
11           System.out.println("出发操作:"+m.div(10,2));
12      }
13  }

throw:在一个有异常中的方法中,可以进行捕获,也可以进行throws

注意throws:一旦被执行,程序就会立即转入异常处理阶段,后面的语句就不再执行了,而且所在的方法不再返回有意义的值.

1 public class TestThrow
 2 {
 3     public static void main(String[] args) 
 4     {
 5         try
 6         {
 7             //调用带throws声明的方法,必须显式捕获该异常
 8             //否则,必须在main方法中再次声明抛出
 9             throwChecked(-3);            
10         }
11         catch (Exception e)
12         {
13             System.out.println(e.getMessage());
14         }
15         //调用抛出Runtime异常的方法既可以显式捕获该异常,
16         //也可不理会该异常
17         throwRuntime(3);
18     }
19     public static void throwChecked(int a)throws Exception
20     {
21         if (a > 0)
22         {
23             //自行抛出Exception异常
24             //该代码必须处于try块里,或处于带throws声明的方法中
25             throw new Exception("a的值大于0,不符合要求");
26         }
27     }
28     public static void throwRuntime(int a)
29     {
30         if (a > 0)
31         {
32             //自行抛出RuntimeException异常,既可以显式捕获该异常
33             //也可完全不理会该异常,把该异常交给该方法调用者处理
34             throw new RuntimeException("a的值大于0,不符合要求");
35         }
36     }
37 }

猜你喜欢

转载自www.cnblogs.com/qingmuchuanqi48/p/10935662.html
今日推荐