User.java
class User{
private int age;
public void setAge(int age){
this.age = age;
}
}
Test.java
class Test{
public static void main(String args []){
User user = new User();
user.setAge(-20);
}
}
显然,我们设置-20,编译器也不会报错,同样顺利编译成功,但是-20不符合我们的逻辑,所以,这里需要自定义一个异常,在上面两文件的基础上作修改:
User.java
class User{
private int age;
public void setAge(int age){
if(age < 0){
RuntimeException e = new RuntimeException("年龄不能为负数");
throw e;
}
this.age = age;
}
}
Test.java不变
编译,运行
这时运行出现了一个异常。
这里使用的是运行时异常的类,RuntimeException 自定义异常需要抛出用throw,终止代码运行。
如果不用RuntimeExcetpion而是用Exception的话,就是编译异常,编译时就会报错。
User.java
class User{
private int age;
public void setAge(int age){
if(age < 0){
Exception e = new Exception("年龄不能为负数");
throw e;
}
this.age = age;
}
}
编译出错,发现有提示,“必须对其进行捕捉或声明以便抛出” 捕捉就是用try catch结构
而声明呢,接下来就给大家演示,同样修改代码
User.java
class User{
private int age;
public void setAge(int age) throws Exception{
if(age < 0){
Exception e = new Exception("年龄不能为负数");
throw e;
}
this.age = age;
}
}
加了throws Exception,
Test.java
class Test{
public static void main(String args []){
User user = new User();
user.setAge(-20);
}
}
可以看到,编译User.java时已经不会报错,但是编译Test.java时就报错,throws Exception的作用就是,将报错的任务交给了调用User这个类的类。
下面用try catch捕捉异常
User.java不变
Test.java
class Test{
public static void main(String args []){
User user = new User();
try{
user.setAge(-20);
}
catch(Exception e){
System.out.println(e);
}
}
}
今天就到这,下次继续。