1、异常处理机制
- 抛出异常:当方法出现错误而引发异常时,方法创建异常对象并交付运行系统,异常对象包含异常类型和异常出现时的程序状态等异常信息。运行系统负责寻找处置异常的代码并执行。
- 捕捉异常:方法抛出异常后,运行系统寻找合适的异常处理器(exception handler)。潜在的异常处理器是异常发生时依次存留在调用栈中方法集合。当异常处理器所能处理的异常类型与方法抛出的异常类型相符时,即为合适的异常处理器。运行系统从发生异常的方法开始,依次回查调用栈中的方法,直至找到含有合适异常处理器的方法并执行。当运行系统遍历调用栈而未找到合适的异常处理器,则运行系统终止。同时,意味着Java程序的终止。
子类异常应先被捕获,易于确定具体的错误类型信息;finally优先于异常中return执行。
public class ExceptionHandleMechanism {
public static int doWork() {
try {
int i = 10 / 0;
System.out.println("i="+i);
} catch (ArithmeticException e) {
// 捕获 ArithmeticException
System.out.println("ArithmeticException: "+e);
return 0;
} catch (Exception e) {
// 捕获 Exception
System.out.println("Exception: "+e);
return 1;
} finally {
System.out.println("Finally");
return 2;
}
}
public static void main(String[] args) {
System.out.println("执行后的值为:"+doWork());
System.out.println("Mission Complete");
}
}
ArithmeticException: java.lang.ArithmeticException: / by zero
Finally
执行后的值为:2
Mission Complete
2、Java异常的处理原则
- 具体明确:抛出异常通过异常类名和message准确说明异常类型和产生异常原因。
- 提早抛出:应尽可能早抛出异常,便于精确定位问题。
- 延迟捕获:异常捕获和处理尽可能延迟,让掌握更多信息的作用域来处理异常。(抛给上层的业务类处理)
3、高效主流的异常处理框架
- 设计一个继承RuntimeException异常统一处理异常类ApplicationException
- catch捕获异常,向上抛出异常子类,并提供足够定位信息给ApplicationException (避免堆栈的错误信息返回)
- 前端接收ApplicationException异常信息统一处理
public class ApplicationException extends RuntimeException {
private String code;
private String msg;
public ApplicationException(String msg) {
super(msg);
this.msg = msg;
}
public ApplicationException(String code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
4、try-catch性能问题
Java异常处理消耗性能的地方
- try-catch块会影响JVM的优化排序
- 异常对象实例化,需要保存栈快照等信息,开销大(重操作:如堆栈信息)
public class ExceptionPerformance {
public static void testException(String[] array) {
try {
System.out.println(array[0]);
} catch (NullPointerException e) {
System.out.println("array cannot be null");
}
}
public static void testIf(String[] array) {
if (array != null) {
System.out.println(array[0]);
} else {
System.out.println("array cannot be null");
}
}
public static void main(String[] args) {
long start = System.nanoTime();
//testException(null);//cost 628300
testIf(null); //cost 278700
System.out.println("cost "+(System.nanoTime() - start));
}
}
Java异常处理详解
本文深入探讨Java异常处理机制,包括异常抛出与捕捉流程、处理原则、高效异常处理框架设计及try-catch性能影响。通过代码示例解析异常处理过程,提出具体明确、提早抛出和延迟捕获的原则,介绍ApplicationException框架实现,并分析try-catch块对性能的影响。
8005

被折叠的 条评论
为什么被折叠?



