为什么Throwable.fillInStackTrace()方法是public?为什么有人会使用它? [英] Why is Throwable.fillInStackTrace() method public? Why would someone use it?

查看:94
本文介绍了为什么Throwable.fillInStackTrace()方法是public?为什么有人会使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么方法 fillInStackTrace java.lang.Throwable public?

I'm curious why is method fillInStackTrace of java.lang.Throwable public?

此方法将从原来的堆栈跟踪替换原来的堆栈跟踪,删除本地化异常所需的信息。它可以用于混淆,但没有太多的努力,因为新的堆栈跟踪将指向混淆代码。更好的方法是简单地隐藏异常或抛出新的异常。

This method replaces original stack trace with that from the place it is called, removing the information needed to localize exception. It could be used for obfuscating, but without much effort, since new stack trace would direct to the obfuscation code. Better way would be to simply hide the exception or throw the new one.

但是我找不到任何合理的案例来调用这个方法存在 Throwable 。所以问题是:为什么这种方法是公开的?有没有什么意义?

But I can't find out any reasonable case for calling this method on existing Throwable. So the question is: why this method is public? Is there any sense behind?

推荐答案

一个原因是表现。投掷和捕捉异常便宜;昂贵的部分是填写堆栈跟踪。如果你覆盖 fillInStackTrace()不做任何事情,创建异常也变得便宜。

One reason is for performance. Throwing and catching an exception is cheap; the expensive part is filling in the stack trace. If you override fillInStackTrace() to do nothing, creating an exception also becomes cheap.

有了便宜的例外,你可以使用流量控制的例外,这样可以使代码在某些情况下更易读;您可以在实现需要 >更高级的流量控制,如果您正在撰写演员图书馆

With cheap exceptions, you can use exceptions for flow control, which can make the code more readable in certain situations; you can use them when when implementing JVM languages where you need more advanced flow control, and they are useful if you are writing an actors library.

这篇关于为什么Throwable.fillInStackTrace()方法是public?为什么有人会使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆