- throw关键字
throw用于抛出具体异常类的对象,一般用于方法体中。
什么时候使用:当所写的代码因不满足某些条件致使程序无法运行时可以借助throw抛出一个异常对象提醒程序员。
import exception.AgeException;
public class Student {
private int age=10;//如果该变量为public级别的变量,则定义Student类的人无法对该变量的范围进行有效的约束 公共方法操作私有属性
public void setAge(int age) {
if(age>=0&&age<=20){
this.age=age;
}
else {
try{
throw new AgeException("无效");//把异常抛给了自己
}catch(AgeException e){
e.printStackTrace();}
}
}
public int getAge() {
return age;
}
}
public class Test {
public static void main(String[] args) {
Student student=new Student();
student.setAge(100);
System.out.println(student.getAge() );
}
}
运行结果如下:
可见是程序把抛给了自己,自己处理了错误
throw关键字一般用在方法体中,也可以用在代码块中,但如果代码块中抛出的异常对象是由检查时异常创建的,则必须使用try-catch进行处理;
throw将异常对象抛给谁
①抛给自己
②抛给方法调用者
package com.jd.vo;
import com.jd.exception.AgeException;
public class Student{
public void setAge( int age){
if (age>1 && age<20) {
this.age = age;
}
else {
throw new AgeException("年龄无效");}//把异常抛给方法调用者
}
public int getAge() {
return age;
}
}
public class Test {
public static void main(String[] args) {
Student student=new Student();
student.setAge(100);
System.out.println(student.getAge() );
}
}
使用throw抛出异常对象如果没有try-catch捕获该异常对象,则该抛出异常对象语句执行后其所在方法结束执行。
如何自定义异常
创建继承Exception 或其子类的自定义类;自定义异常类调用父类构造函数(通常是含有一个String类型参数的构造函数);
throw用于抛出异常对象:
1、如果异常对象为运行时,则方法参数列表后面可以不是使用throws,也可以将异常抛给方法调用者;try-catch
2、如果异常对象为检查时,则方法参数列表后面必须使用throws抛出创建该对象的类;如果没哟uthrows 必须try-cacth
- throws关键字
throws用于声明方法可能抛出的异常,其后为异常类,可以有多个,异常类之间用英文逗号间隔。
什么时候使用:
①当方法体中的throw关键字抛出由检查时异常创建的对象时,如果该异常对象在抛出的同时已经通过try-catch进行了处理,则可
以不使用throws,否则必须使用throws抛出创建该对象的异常类或其父类。
②所调用的方法抛出了检查时异常时,如果该方法在调用的同时已经通过try-catch进行了处理,则可以不使用throws继续上抛该
异常,否则必须使用throws才能上抛该异常,此时上抛的异常类可以是调用方法时方法抛出的异常类也可以是其父类。
注意:
如果方法中的异常已经通过try-catch进行了捕获则无需再使用throws上抛该异常了,否则即使上抛也无效,只会做无用功。
public class Test{
public static void show(int age) throws PrinterException{
if(age<0||age>150){
try {
throw new PrinterException(“操作失败:年龄取值范围为0~150”);//此处异常已经通过try-catch语句进行了处理,所以show方法无需再使用throws抛出异常了,否则即使上抛也无效:执行代码会发现,即使这里异常被触发了,在main方法中catch依然没有执行,所以此时在通过throws抛出异常类纯属无用功
} catch (PrinterException e) {
System.out.println("show方法");
e.printStackTrace();
}
return;
}
System.out.println(age);
}
public static void main(String[] args) {
try {
show(1000);
} catch (PrinterException e) {
System.out.println("main方法");
e.printStackTrace();
}
}
}
如果方法中的代码或者方法中所调用的代码没有使用throw抛出异常类对象,则无需使用throws否则该throws所抛出的异常类无效:即使用throws则其方法中的代码一定存在使用throw抛出异常对象的代码。
public class Test {
public static void show(int data)throws Exception{//由于该方法中只是一个简单的输出语句,方法体和方法体中所调用的方法均没有使用throw抛出异常对象,所以此处没有必要使用throws抛出异常类,即便抛出了也是无用的——由于这里使用了throws抛出了异常类,main方法对该异常类进行了处理,可是我们会发现main方法中的catch语句块永远不可能执行
System.out.println(data);
}
public static void main(String[] args) {
try {
show(100000);
} catch (Exception e) {
System.out.println("永远不会执行");
e.printStackTrace();
}
}
}
- throw与throws的区别
①抛出的东西不同:throw抛出的是具体的异常对象,而throws抛出的是抽象的异常类;
②使用位置不同:throw一般用在方法体中,也可用在代码块中,但是如果抛出的是检查时异常类创建的对象,则必须使用try-catch自行处理;throws只能用在方法声明括号后面;