不,不要这样做.昂贵的部分没有处理异常,它正在生成堆栈跟踪.不幸的是,堆栈跟踪也是有用的部分.如果你抛出一个保存的异常,你会传递一个误导的stacktrace.
可能在Scala的实施过程中,有这样的情况是有道理的. (也许他们正在做一些递归的事情,想要提前生成一个异常对象,以防它们内存不足,它们仍然可以产生异常.)他们还有很多关于他们在做什么的信息,所以他们有更好的机会得到正确的但是JVM语言实现者所做的优化是一个非常特殊的例子.
所以你不会打破任何事情,除非你认为提供有误导性的信息是破损的.对我来说似乎是一个很大的风险.
尝试Thomas Eding关于如何创建没有堆栈跟踪的异常的建议似乎有效:
groovy:000> class MyException extends Exception {
groovy:001> public Throwable fillInStackTrace() {}}
===> true
groovy:000> e = new MyException()
===> MyException
groovy:000> Arrays.asList(e.stackTrace)
===> []
另请查看JLS:
The NullPointerException (which is a kind of RuntimeException) that is
thrown by method blowUp is not caught by the try statement in main,
because a NullPointerException is not assignable to a variable of type
BlewIt. This causes the finally clause to execute,after which the
thread executing main,which is the only thread of the test program,
terminates because of an uncaught exception,which typically results
in printing the exception name and a simple backtrace. However,a
backtrace is not required by this specification.
The problem with mandating a backtrace is that an exception can be created at one point in the program and thrown at a later one. It is prohibitively expensive to store a stack trace in an exception unless it is actually thrown (in which case the trace may be generated while unwinding the stack). Hence we do not mandate a back trace in every exception.
本文探讨了在Scala等语言中处理异常时保留堆栈跟踪的重要性,并提供了在不需要堆栈跟踪的情况下创建异常的方法。
33万+

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



