代码和结果如下:
public class TryCatchTest { public static void main(String[] args) { long start = System.nanoTime(); int a = 0; for (int i = 0; i < 1000000; i++) { try { a=1/0; // a=1/1; } catch (Exception e) { e.printStackTrace(); } } System.out.println((System.nanoTime() - start)); /** * 异常打印22,200,801,025纳秒 即22秒 * 异常不打印283,239,909纳秒 即283毫秒 * 无异常3,966,408纳秒 即4毫秒 * 1毫秒=1,000,000纳秒 */ } }
项目中,有的同事喜欢抛出异常,再统一收集异常并转换为状态码再返回。
如果是一般的程序,对性能没什么要求,这点性能损耗也不是那么不能接受,反而这样做还显得耦合性低,比较优雅。
但是对性能要求非常苛刻的场景,特别是存在被人刻意伪造异常进行攻击的风险,不建议以捕捉异常的形式来返回业务上的错误。
慢的原因:异常发生时,需要收集栈跟踪,放在对象e中。不管你是否打印这个栈跟踪,都会做。这个动作相对来说比较耗时。