try catch exception注意点
1:throw e
public static void main(String[] args) {
try {
int aa = 1 / 0;
} catch (Exception e) {
throw e;
}
int i = 4 / 2;
System.out.println("失败和成功!!!"+i);
}
throw e 会阻断后续程序的运行!!!!!
2: e.printStackTrace(); 或其他日志输出
public static void main(String[] args) {
try {
int aa = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
}
int i = 4 / 2;
System.out.println("失败和成功!!!"+i);
}
不会阻断后续程序的执行!!!!!
3: throws NumberFormatException 交给上一层去解决
public static void function() throws NumberFormatException{
String s = "abc";
System.out.println(Double.parseDouble(s));
}
public static void main(String[] args) {
try {
function();
} catch (NumberFormatException e) {
System.err.println("非数据类型不能转换。");
//e.printStackTrace();
}
}
交给main方法中去处理异常
4:多个catch 异常的情况
1/0报错会直接跳到ArithmeticException,后面4/2就不会执行。而且捕捉到ArithmeticException后那个exception异常就不管了。这种注意Exception这个异常一定要放到最后!!!
