如何确定哪个函数调用在 try 块中引发了特定异常?
假设一个 try
块中有 3 个连续的函数调用,并且它们都抛出相同类型的异常。我如何找出哪个函数调用在处理它时引发了捕获的异常?
Let's say there are three consecutive function calls in one try
block and all of them throw the same type of exception. How can i figure out which function call threw the caught exception when handling it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在每个方法调用周围放置一个 try-catch 块。
或者您查看异常堆栈跟踪。它们描述了哪一行代码引发了异常。
编辑:
Throwable
StackTraceElement
You can put a try-catch block around every single method call.
Or you take a look at the exception stack trace. Their is described which line of code throwed the exception.
EDIT:
Throwable
StackTraceElement
像这样:
like this:
所以我猜测您的代码中的某些内容使明显的解决方案变得棘手,也许方法调用站点向下一两个级别,或者不在同一级别?到底是什么阻止你只保留一个计数器?
在任何情况下,您都需要计算调用次数,使用多个 try 块,或者执行此操作并定义自己的异常,其中包含丢失的信息(以及旧异常,因为它是子类),然后重新抛出它。
也许您可以使用异常抛出方法对对象进行子类化,以便包装方法调用并实现计数器?
So I'm guessing that something about your code makes the obvious solutions tricky, perhaps the method call sites are a level or two down, or not at the same level? What exactly prevents you from just keeping a counter?
In any case, you need to either count invocations, use multiple try blocks, or do that and define your own exception which contains the missing information (and the old exception, because it's a subclass) and then rethrow it.
Perhaps you could subclass the object with the exception-throwing method, in order to wrap the method call and implement the counter?
我认为内省堆栈跟踪来进行错误处理会给你带来非常严重的伤害。如果您需要对单独的行进行单独的操作,请将它们放在单独的 try-catch 块中。
您可能还只想有一个简单的变量来保持状态,这样您就可以检查该值,以确定您走了多远。我认为这样会效果更好。
编辑
:反对者,请注意我开始说这是一个坏主意;-)
I think introspecting the stack trace to do error handling will hurt you very badly later. If you need separate actions for separate lines, then have them in individual try-catch blocks.
You may also just want to have a simple variable keeping state, so you can check on the value, to determine how far you got. I think that will work much better.
}
Edit: Downvoters, please notice I started saying this is a bad idea ;-)