异常:中断了正常指令流的事件
运行时的错误,不是编译时出现的错误,异常是在运行中产生的,即是编译已经通过了。
thorw虚拟机判断不了,throw出异常;
thorws申明一个函数有可能产生异常,函数不处理异常,而是调用函数的地方进行异常处理;
class User
{
public void setAge(int age)throws Exception{
if(age<0){
Exception e=new Exception("年龄不能为负数");
throw e;
}
this.age = age;
}
}
class Test
{
public static void main(String args[]){
User user = new User();
try{
user.setAge(-20);
}
catch(Exception e){
System.out.println(e);
}
}
}