1 异常中的一些细节
1.1 Throwable的常用方法
-
我们所学的异常的本质, 是异常对象,是一种异常情况的描述
-
对象一般都具有一些方法。 所以异常对象也有一些方法
-
异常对象的绝大多数方法都来自于Throwable
e.getMessage() //获得异常的具体描述信息,也是创建异常对象时传递的那个msg //打印完整的异常信息 // 1. 异常类型 // 2. 具体的异常描述(message) // 3. 异常产生及向上抛出的行程 //注意: 看到这样的错误栈信息,不代表程序出错了。 e.printStackTrace(); //为当前异常提供一个原因,这个原因依然是一个异常对象 //该方法的使用一般多在框架中。 e.initCause(otherException); public class Test2 { public static void main(String[] args) {//主方法向根据一个人的工资总量,计算月平均工资//已知 员工:zs ,目前工资总数1w//需要知道zs干了几个月getMonth("zs"); } //根据员工姓名,获得该员工工作的时长(月数)public static int getMonth(String name){//先获得员工对象//获得员工的入职时间//根据当前系统时间,计算工作的月数try {getEmp(name);return 3 ;}catch (NullPointerException e){ArithmeticException e2 = new ArithmeticException("无法计算工作的月数");e2.initCause(e);throw e2 ;}} //根据员工的名字,获得员工对象(包含了员工入职时间)public static Object getEmp(String name){//所有员工信息都存储在一个文件中(数据库中)//需要从文件中获取所有员工信息,并找到当前name名字的员工信息try {findEmpFile("");return null ;}catch (FileNotFoundException e){//一旦有了问题,当前这个方法还能给调用者返回name对应的emp对象么?NullPointerException e2 = new NullPointerException("没找到"+name+"这个员工") ;e2.initCause(e);throw e2 ;}} //找到存储员工的文件,将文件中存储的所有员工信息返回public static Object[] findEmpFile(String path)throws FileNotFoundException{//根据路径找文件时,发现文件不存在throw new FileNotFoundException("存储员工的文件不存在");} }
1.2 try-catch-finally组合应用
try{}catch(Exception e){}try{}catch(Exception1 e){}catch(Exception2 e){}catch(Exception e){}try{a
}catch(Exception1 e){b
}catch(Exception2 e){c
}finally{d
}
编码时,try,catch,和finally是分块的编译时, finally中的代码会分别与try 和 catch组合try{ad
}catch(Exception1 e){bd
}catch(Exception2 e){cd
}
//try和catch中有return时,finally中的代码还会不会执行? 会
try{dreturn 1 ;d
}catch(Exception e){return 2 ;
}finally{d
}
//try,catch,finally中都有return时,最终返回的哪里的return值呢? finally中
try{//1压栈//3压栈//return 栈顶的数据return 1 ;d
}catch(Exception e){return 2 ;
}finally{//3压栈//return 栈顶的数据return 3
}
void t1(){try{//return 1 ;throw new NullPointerException();}catch(Exception e){throw new ArrayIndexOutOfBoundsException();}finally{return 1 ;}
}
void t2(){t1(); //得到什么? 1
}try{}finally{}