简体   繁体   English

如何防止调用者捕获我的异常

[英]How to prevent caller from catching my exceptions

I wrote a safeMethod() which should not throw any exceptions, and if it does, I want to crash the app (to get them reported via crash monitoring system).我写了一个safeMethod() ,它不应该抛出任何异常,如果抛出异常,我想让应用程序崩溃(通过崩溃监控系统报告它们)。

The problem is, I need to call this method from library callback which is wrapped in try/catch up the call stack .问题是,我需要从包装在try/catch up the call stack 中的库回调中调用此方法。

I tried to "raise stakes":我试图“加注”:

try {
    safeMethod();
} catch (Exception e) {
    throw new Throwable(e);
}

But this does not compile because overridden method does not declare throws Throwable .但这不会编译,因为重写的方法没有声明throws Throwable

The other thing that comes to my mind is to use some asynchrony, for example:我想到的另一件事是使用一些异步,例如:

new Handler().post(() -> safeMethod());  // Handler is Android class to work with thread's message queue

or要么

new Thread(() -> safeMethod()).start();

It works, but seems like an overkill, complicating control flow and wasting resources.它有效,但似乎有点矫枉过正,使控制流程复杂化并浪费资源。

Are there any better ways?有没有更好的方法?

I searched here and on the web for "prevent catching exception", "override catch block", "force throw exception" and so on, but found nothing relevant.我在这里和 web 上搜索了“防止捕获异常”、“覆盖 catch 块”、“强制抛出异常”等,但没有找到任何相关内容。 Not even unanswered questions.甚至没有悬而未决的问题。 Numerous advices to catch only specific exceptions are not very useful in this case.在这种情况下,许多仅捕获特定异常的建议不是很有用。 ;) ;)

I can suggest two options:我可以建议两个选项:

  1. Throw an Error抛出Error
  2. System.exit(1);

It is up to you which one to choose the main difference is that throwing an error will give you a stack trace and then do System.exit(1) .选择哪一个取决于你,主要区别在于抛出错误会给你一个堆栈跟踪,然后执行System.exit(1)

It is important to call System.exit with something different then 0 to show an error situation.使用不同于 0 的值调用System.exit以显示错误情况很重要。

Normally it is not recommended to throw Errors but your case might be an exception from that rule.通常不建议抛出错误,但您的情况可能是该规则的例外。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM