自定义异常语法:
class 自定义异常 extends 异常类型{
//构造方法
}
注:
自定义异常所继承的异常类型必须为Java标准类库中意思相近的异常类型,或者直接继承于所有异常类型的基类(即Exception类型)
例如:
import java.util.Scanner;
class DefinedException extends Exception{
public DefinedException() { //无参构造器
super();
}
public DefinedException(String message) { //含参构造器
super(message);
}
}
public class Test{
public static void main(String[] args){
System.out.println("请输入血压值:");
Scanner in=new Scanner(System.in);
int low=in.nextInt();
int high=in.nextInt();
try {
defined(high, low);
} catch (DefinedException e) {
System.out.println(e.getMessage());
}
}
public static void defined(int high,int low) throws DefinedException{
if(low>60&&high<139){
System.out.println("血压值正常");
}
else{
throw new DefinedException("血压值异常");
}
}
}
运行结果:
请输入血压值:
50 80
血压值异常