java中的抛出异常_在Java中总是抛出异常异常

本文探讨了在Scala等语言中处理异常时保留堆栈跟踪的重要性,并提供了在不需要堆栈跟踪的情况下创建异常的方法。

不,不要这样做.昂贵的部分没有处理异常,它正在生成堆栈跟踪.不幸的是,堆栈跟踪也是有用的部分.如果你抛出一个保存的异常,你会传递一个误导的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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值