标签:blog http io ar 使用 java sp div on
uncheckException的处理
class User{
private int age;
public void setAge(int age){
if(age < 0){
//生成异常对象
RuntimeException e = new RuntimeException("年龄不能为负数");
throw e; //终止运行,抛出异常对象
}
this.age = age;
}
}
class Test{
public static void main(String args[]){
User u = new User();
u.setAge(-20);
}
}
JVM不能识别的异常,比如年龄为负数,在语法上没有错误但不符合实际,需要靠人为识别异常,生成异常对象,通过throw抛出异常。JVM得到异常对象后则终止代码运行。
checkException的处理
class User{
private int age;
public void setAge(int age){
if(age < 0){
Exception e = new Exception("年龄不能为负数");
throw e;
}
this.age = age;
}
}
捕获:使用try…catch…finally
声明:使用throws
当setAge方法有可能产生checkException时,如Exception类型的异常,在函数后面添加throws声明Exception这样的异常对象,产生异常后由调用setAge方法的地方来处理。
class User{
private int age;
public void setAge(int age) throws Exception{
if(age < 0){
Exception e = new Exception("年龄不能为负数");
throw e;
}
this.age = age;
}
}
再次编译Test.java时提示如下错误:

class Test{
public static void main(String args[]){
User u = new User();
try{
u.setAge(-20);
}
catch(Exception e){
e.printStackTrace();
}
}
}

当在User类中的setAge方法后通过throws声明异常类型后,Test主函数中调用了setAge方法产生了异常并用try…catch进行处理。
总结:
Throw的作用:JVM无法判断的异常,可通过生成异常对象用thorw抛出异常
Throws的作用:用来声明一个函数可能会产生异常,函数不对异常进行处理,调用函数的地方对异常进行处理。
标签:blog http io ar 使用 java sp div on
原文地址:http://www.cnblogs.com/chavez-wang/p/4074854.html