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 }

       

         

  • 相关阅读:
    shell流程控制
    shell编程变量介绍与表达式详解
    shell编程简介
    反向代理与负载均衡
    存储库之mongodb,redis,mysql
    请求库之requests,selenium
    解析库之re、beautifulsoup、pyquery
    爬虫基本原理
    Django 函数和方法的区别
    Django 知识补漏单例模式
  • 原文地址:https://www.cnblogs.com/iMirror/p/3740602.html
Copyright © 2011-2022 走看看