异常图解
捕获异常有三种格式:①try-catch 语句;②try-catch-finally 语句;③try-finally 语句。
如果在try 或者 catch 中存在return 语句,这时finally语句还是会执行,且在return 语句前执行,执行后再执行return。
throws 与 throw 的区别
throws 是在方法的后面抛出异常的声明,语法:[(修饰符)](返回值类型)(方法名)([参数列表])[throws(异常类)]{......}
public void doA(int a) throws Exception1,Exception3{......}
throw是抛出一个异常类,语法:throw (异常对象); 如自定义异常、空指针异常等。
用户自定义异常类,只要使用自定义异常类是Exception的子类即可,开发步骤为:
1.创建自定义异常类。继承Exception
2.在方法中通过throw关键字抛出异常对象。
使用自定义异常:
a) 编写如下异常类:空异常。年龄低异常、年龄高异常、身份证非法异常。
b) 编写员工类:
i. 有编号、姓名、年龄和身份证号等属性;
ii. 构造器1:初始化编号、姓名、年龄,如果名字为空,抛出空异常;如果年龄小于18,抛出年龄低异常;如果年龄高于60,抛出年龄高异常;
iii. 构造器2:初始化身份证号,使用正则表达式来匹配,如果不是合法的身份证号,抛出身份证非法异常;
c)写一个测试类来验证这些异常。
import java.util.regex.Pattern;
public class Excep {
public static void main(String[] args) {
Employee em = new Employee("001", "小明", 20, "51132219941018437");
try {
em.EX();
} catch (NullException e) {
System.out.println(e.warnMess());
}catch(AgeLowException e){
System.out.println(e.warnMess());
}catch(AgeHighException e){
System.out.println(e.warnMess());
}catch(IdIlleagleException e){
System.out.println(e.warnMess());
}
System.out.println("111");
}
}
class Employee{
String ID;
String name;
int age;
String IdCard;
public Employee(String id,String n,int a,String ic) {
this.ID = id;
this.name = n;
this.age = a;
this.IdCard = ic;
}
public void EX() throws NullException,AgeLowException,AgeHighException,IdIlleagleException{
if(this.name.isEmpty()){
throw new NullException();
}
if(this.age < 18){
throw new AgeLowException();
}
if(this.age > 60){
throw new AgeHighException();
}
boolean control =
Pattern.matches("\\d{17}[[0-9]*[a-z]*]{1}",this.IdCard);
if(!control){
throw new IdIlleagleException();
}
}
}
class NullException extends Exception{
String message;
public NullException(){
message="空异常";
}
public String warnMess(){
return message;
}
}
class AgeLowException extends Exception{
String message;
public AgeLowException() {
message = "年龄低异常。。。";
}
public String warnMess(){
return message;
}
}
class AgeHighException extends Exception{
String message;
public AgeHighException() {
message = "年龄高异常。。。";
}
public String warnMess(){
return message;
}
}
class IdIlleagleException extends Exception{
public String message;
public IdIlleagleException() {
message="身份非法异常。。。";
}
public String warnMess(){
return message;
}
}