Java异步异常:我可以抓住他们吗? [英] Java Asynchronous Exceptions: Can I catch them?

查看:973
本文介绍了Java异步异常:我可以抓住他们吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读JLS,我遇到了 11.1.3。异常异常引用:

I have been reading the JLS and I encountered the section 11.1.3. Asynchronous Exceptions from which I quote:


大多数异常由于
线程的动作而同步发生并且在程序中指定
的某一点可能导致这种异常。相反,一个异步的
异常是执行程序中任何一点可能发生在
的异常。

Most exceptions occur synchronously as a result of an action by the thread in which they occur, and at a point in the program that is specified to possibly result in such an exception. An asynchronous exception is, by contrast, an exception that can potentially occur at any point in the execution of a program.


异步异常仅发生在以下情况:

Asynchronous exceptions occur only as a result of:

[...]


  • Java虚拟机中的内部错误或资源限制阻止其执行$的语义b $ b Java编程语言。在这种情况下,抛出的异步异常
    是VirtualMachineError子类的一个实例。

是否有可能捕获此类异常记录目的或通知(因为我认为这样的事情是不可恢复的)?如何实现这样的事情?

Is it possible to catch such exceptions for logging purposes or notification (because I believe such thing is unrecoverable)? How can I achieve such thing?

推荐答案

您可以像任何其他异常一样捕获这样的异常。唯一的问题是它们可能发生在程序中的任何位置,因此可靠地抓住它们是困难的。您将基本上必须在中包装所有线程的运行方法和 main try..catch 阻止,但是您不能为不能控制的线程(如Swing EDT或定时器的线程等)执行此操作。

You can catch such exceptions just like any other exception. The only problem is that they may occur at any place in your program, so catching them reliably is hard. You would basically have to wrap the run method of all threads and the main method in a try..catch block, but you can't do that for threads you don't control (like the Swing EDT, or threads for timers etc.).

通常不推荐使用错误的任何子类,因为JVM可能处于不稳定状态,这可能会导致进一步的故障(例如在 OutOfMemoryError 的情况下,甚至可能没有足够的内存来处理异常。但是,日志记录是捕捉我的眼睛中错误的有效理由。

Also catching any subclass of Error is usually not recommended, because the JVM may be in an unstable state, which might lead to a further failure (for example in the case of OutOfMemoryError, you might not even have enough memory to to the exception handling). However, logging would be a valid reason for catching Errors in my eyes.

我建议的解决方案是使用未捕获的异常处理程序,由将其设置为默认异常处理程序。在这个处理程序中,你会得到所有的异常和错误,如果它们没有在代码中的任何地方被捕获,你可以尝试登录。

My suggested solution would be to use an uncaught exception handler for this by setting it as the default exception handler. In this handler you will get all exceptions and errors, if they are not caught anywhere in the code, and you can try to log them.

这篇关于Java异步异常:我可以抓住他们吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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