Java当中的异常(二)

1. throw 的作用

2. throws 的作用

1. throw的作用  

 1 class User{
 2     private int age;
 3     public void setAge(int age){
 4         if (age < 0){
 5             RuntimeException e = new RuntimeException("年龄不能小于0"); //生成异常对象需要异常类    
6 throw e ;//throw就是抛出异常
7 } 8 this.age = age ; 9 } 10 }
1 class Test{
2     public static void main(String args []){
3         User user = new User();
4         user.setAge(-20);
5     }
6 }

                 

2. throws 的作用

      上一节分类中, Exception 分为 RuntimeException 和其他的异常, RuntimeException可以使用throw直接抛出

      其他的则可使用 try..catch..finally 直接在函数内处理

                           或者 使用 throws声明 Exception 让调用它的函数去处理

 1 class User{
 2     private int age;
 3     public void setAge(int age) throws Exception{//throws将异常抛给调用它的函数处理
 4         if (age < 0){
 5             Exception e = new Exception("年龄不能小于0");
 6             throw e ;
 7         }
 8         this.age = age ; 
 9     }
10 }
 1 class Test{
 2     public static void main(String args []){
 3         User user = new User();
 4         try{
 5             user.setAge(-20);
 6         }
 7         catch(Exception e){
 8             System.out.println(e);
 9         }
10     }
11 }

   

     

原文地址:https://www.cnblogs.com/iMirror/p/3740602.html