zoukankan      html  css  js  c++  java
  • 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 }

       

         

  • 相关阅读:
    ADL(C++参数依赖查找)
    Sublime Text3 + Golang搭建开发环境
    Zookeeper使用命令行(转载)
    软链接和硬链接(转载)
    kafka伪集群搭建
    使用librdkafka库实现kafka的生产和消费实例生产者
    vector和map使用erase删除元素
    jquery html函数的一个问题
    贪心类区间问题
    快速幂
  • 原文地址:https://www.cnblogs.com/iMirror/p/3740602.html
Copyright © 2011-2022 走看看