- throw的作用
throw + 异常对象
class User{
private int age;
public void setAge(int age){
**if(age < 0){
RuntimeException e =new RuntimeException(“年龄不能为负数”);
throw e;
}**
this.age = age;
}
}
在虚拟机无法辨识异常的时候,将异常对象抛出。必须注意此类问题是虚拟机不能识别的 - 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;
}
}
java31java当中的异常(二)
最新推荐文章于 2024-07-05 07:15:00 发布