java31java当中的异常(二)

来源:互联网 发布:各种算法的时间复杂度 编辑:程序博客网 时间:2024/05/16 17:09
  1. throw的作用
    throw + 异常对象
    class User{
    private int age;
    public void setAge(int age){
    **if(age < 0){
    RuntimeException e =new RuntimeException(“年龄不能为负数”);
    throw e;
    }**
    this.age = age;
    }
    }
    在虚拟机无法辨识异常的时候,将异常对象抛出。必须注意此类问题是虚拟机不能识别的
  2. throws的作用
    在可能产生check异常的函数中可以选择在函数中处理,也可以对异常的产生进行声明。谁调用异常函数谁对异常进行try catch处理!
    class TestU{
    public static void main(String[] args){
    User u = new User();
    try{
    u.setAge(-20);
    **}
    catch(Exception e){**
    **System.out.println(e);
    }**
    }
    }
    thows的声明作用:
    class User{
    private int age;
    public void setAge(int age) throws Exception{
    if(age < 0){
    Exception e =new Exception(“年龄不能为负数”);
    throw e;
    }
    this.age = age;
    }
    }
0 0