简体   繁体   English

Java - 我可以反思地发现我是否从catch块中的函数调用了partifuclar异常?

[英]Java - can I reflectively find out if I'm being called from a function within a catch block for a partifuclar exception?

First of all, I want to make something clear before I get yelled at: I have no plans to write any code that will ever use this sort of control flow; 首先,在我被大吼之前,我想要明确一些事情:我没有计划编写任何能够使用这种控制流程的代码; its obviously terrible. 它显然很可怕。 Forget about a use case, this is more a question about whether its possible or not: 忘记一个用例,这是一个关于它是否可能的问题:

I want to know if its possible to know if somewhere up the call stack, a function is being called within a catch block for a particular exception. 我想知道是否有可能知道调用堆栈的某个位置,是否在catch块中为特定异常调用了一个函数。

Let's say I have a function: 假设我有一个功能:

foo() {
try {
    something
}
catch (SuperException s) {
    bar()
}

So given NO control over the method signature of bar, and given bar is also called by many other functions, can bar behave differently if called in catch block catching a superexception? 因此,如果没有对bar的方法签名的控制,并且给定的bar也被许多其他函数调用,那么如果在catch块中调用超级函数,那么bar的行为会不同吗? (and no, being called by foo isn't a sufficient condition, its the super exception that matters) (并且不,被foo调用不是一个充分条件,它是重要的超级例外)

You can look at the call stack and get the line numbers of each call. 您可以查看调用堆栈并获取每个调用的行号。

You can read the byte code to determine where the catch blocks are and which lines of code are in those blocks. 您可以读取字节代码以确定catch块的位置以及这些块中的代码行。

Match the two together to see if anywhere in the call stack is in a catch block. 将两者匹配在一起以查看调用堆栈中的任何位置是否在catch块中。

Note: this will only work if you have debug information compiled in your code. 注意:只有在代码中编译了调试信息时,这才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java - 从反射调用的构造函数中捕获异常 - Java - Catching an exception from a reflectively called constructor 如何从 Java 反射性地调用 Scala object 上的方法? - How can I reflectively call a method on a Scala object from Java? 我可以反射性地从 Java 调用一个 Kotlin 协程并将其包装在 CompletableFuture 中吗? - Can I invoke a Kotlin coroutine from Java reflectively and wrap it in CompletableFuture? 我在 Try-Catch 块中找不到正确的异常 — Android Studio Java - I can't find the right exception in Try-Catch Block — Android Studio Java 如何从Java反射性地获取Scala对象上的字段? - How can I reflectively get a field on a Scala object from Java? 我可以反射地实例化Java中的泛型类型吗? - can I reflectively instantiate a generic type in java? 如何在不引发异常的情况下从 try/catch 块中中断 Java - How can I break from a try/catch block without throwing an exception in Java 如何找出,如果在java中从catch块调用相同的方法? - How to find out , if same method is getting called from catch block or not in java? 我可以避免Java中的catch块吗? - Can I avoid catch block in Java? Java,Mockito-如何找出调用了哪些模拟? - java, mockito - how can i find out which mocks are called?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM