未捕获 Java 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1375113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:18:52  来源:igfitidea点击:

Java exception not caught

javaexceptiontry-catch

提问by C. Ross

Why are some exceptions in Java not caught by catch (Exception ex)? This is code is completely failing out with an unhandled exception. (Java Version 1.4).

为什么 Java 中的某些异常没有被 捕获catch (Exception ex)?这是代码因未处理的异常而完全失败。(Java 版本 1.4)。

public static void main(String[] args) {
    try {
        //Code ...
    } catch (Exception ex) {
        System.err.println("Caught Exception");
        ex.printStackTrace();
        exitCode = app.FAILURE_EXIT_CODE;
    }
    finally {
        app.shutdown();
    }
    System.exit(exitCode);
}

I get a Exception in thread "main" java.lang.NoSuchMethodError

我得到一个 Exception in thread "main" java.lang.NoSuchMethodError

But this works

但这有效

public static void main(String[] args) {
    int exitCode = app.SUCCESS_EXIT_CODE;
    try {
        //Code ...
    } catch (java.lang.NoSuchMethodError mex){
        System.err.println("Caught NoSuchMethodError");
        mex.printStackTrace();
        exitCode = app.FAILURE_EXIT_CODE;
    } catch (Exception ex) {
        System.err.println("Caught Exception");
        ex.printStackTrace();
        exitCode = app.FAILURE_EXIT_CODE;
    }
    finally {
        app.shutdown();
    }
    System.exit(exitCode);
}

I get Caught NoSuchMethodError java.lang.NoSuchMethodError:

我得到 Caught NoSuchMethodError java.lang.NoSuchMethodError:

I thought catching exceptions would catch all exceptions? How can I catch all exceptions in java?

我以为捕获异常会捕获所有异常?如何捕获java中的所有异常?

采纳答案by Jon Skeet

Because some exceptions don't derive from Exception- e.g. Throwableand Error.

因为某些异常不是源自Exception- 例如ThrowableError

Basically the type hierarchy is:

基本上类型层次结构是:

       Object
         |
      Throwable
     /         \
Exception      Error

Only Throwablesand derived classes can be thrown, so if you catch Throwable, that really will catch everything.

只能Throwables抛出和派生类,所以如果你 catch Throwable,那真的会抓住一切。

Throwable, Exceptionand any exception deriving from Exceptionotherthan those derived from RuntimeExceptioncount as checked exceptions- they're the ones that you have to declare you'll throw, or catch if you call something that throws them.

ThrowableException以及任何异常,从获得Exception其他比那些源自RuntimeException数作为检查的异常-他们是的,你必须声明你扔了,或者捕捉如果你调用的东西,抛出他们。

All told, the Java exception hierarchy is a bit of a mess...

总而言之,Java 异常层次结构有点混乱......

回答by akf

You can catch Throwable. Error and Exception extend Throwable.

你可以赶上Throwable。错误和异常扩展Throwable

see the Throwable JavaDoc:

请参阅 Throwable JavaDoc

The Throwable class is the superclass of all errors and exceptions in the Java language.

Throwable 类是 Java 语言中所有错误和异常的超类。

回答by Carl Manaster

Exception is just one kind of Throwable; NoSuchMethodError is not an Exception, but an Error, which is another kind of Throwable.

Exception 只是一种 Throwable;NoSuchMethodError 不是Exception,而是Error,是另一种Throwable。

回答by JasCav

As both other posts point out, catch(Exception e) will only work for exceptions that derive from Exception. However, if you look at the tree hierarchy, you'll notice that an Exception if Throwable. Throwable also is the base class for Erroras well. So, in the case of NoSuchMethodError, it is an Error and not an Exception. Notice the naming convention *Error vs. *Exception (as in IOException, for example).

正如其他两个帖子所指出的那样, catch(Exception e) 仅适用于派生自Exception 的异常。但是,如果您查看树层次结构,您会注意到一个 Exception if Throwable。Throwable 也是Error的基类。因此,在 NoSuchMethodError 的情况下,它是一个错误而不是异常。请注意命名约定 *Error 与 *Exception(例如在 IOException 中)。

回答by Simon Nickerson

As other posters have pointed out, not all throwable objects are subclasses of Exception. However, in most circumstances, it is not a good idea to catch Erroror Throwable, because these conditions include some really serious error conditions that cannot easily be recovered from. Your recovery code may just make things worse.

正如其他海报指出的那样,并非所有可抛出的对象都是Exception. 但是,在大多数情况下,捕获Error或并不是一个好主意Throwable,因为这些情况包括一些无法轻易恢复的非常严重的错误情况。您的恢复代码可能只会让事情变得更糟。

回答by Powerlord

Errors aren't Exceptions.

Errors 不是Exceptions。

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

Exception 类及其子类是 Throwable 的一种形式,它指示合理的应用程序可能想要捕获的条件。

-- JavaDoc for java.lang.Exception

--用于 java.lang.Exception 的 JavaDoc

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.

Error 是 Throwable 的一个子类,它指示合理的应用程序不应尝试捕获的严重问题。

-- JavaDoc for java.lang.Error

-- java.lang.Error 的 JavaDoc

There are certain errors that you may want to catch, such as ThreadDeath. ThreadDeath is classified as an Error, as explained below

您可能希望捕获某些错误,例如ThreadDeath。ThreadDeath 被归类为错误,如下所述

The class ThreadDeath is specifically a subclass of Error rather than Exception, even though it is a "normal occurrence", because many applications catch all occurrences of Exception and then discard the exception.

ThreadDeath 类特别是 Error 而不是 Exception 的子类,即使它是“正常发生”,因为许多应用程序捕获所有出现的 Exception 然后丢弃该异常。

-- JavaDoc for ThreadDeath

-- ThreadDeath 的 JavaDoc

However, since Thread's stop() method is now deprecated, you should not use it, and thus you should never see ThreadDeath.

但是,由于 Thread 的 stop() 方法现在已被弃用,您不应该使用它,因此您永远不会看到 ThreadDeath。

回答by Danger

First let's clear up some unfortunate semantic confusion in this discussion. There is the java.lang.Exceptionclass which we can refer to simply as Exception with a capital 'E'. Then you have exception with a lowercase 'e' which is a language feature. You can see the lower case version in the documentationfor the Throwableclass:

首先让我们澄清一些在这个讨论中令人遗憾的语义混淆。有一个java.lang.Exception类,我们可以简单地将其称为带有大写字母“E”的 Exception。然后你有一个小写的“e”例外,这是一种语言特征。您可以在该类的文档中看到小写版本Throwable

For the purposes of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.

出于编译时异常检查的目的,Throwable 和 Throwable 的任何子类(不是 RuntimeException 或 Error 的子类)都被视为已检查异常。

For me it's easier to think about the answer to this question as checked vs. unchecked exceptions (lower case e). Checked exceptions must be considered at compile time, whereas unchecked exceptions are not. Exception (uppercase E) and it's subclasses are checked exceptions, which means you either have to catch any exception that can be thrown by your code, or declare the exceptions that your method could throw (if not caught).

对我来说,更容易将这个问题的答案考虑为已检查与未检查异常(小写 e)。在编译时必须考虑已检查异常,而未检查异常则不然。异常(大写 E)及其子类是受检异常,这意味着您要么必须捕获代码可能抛出的任何异常,要么声明您的方法可能抛出的异常(如果未捕获)。

Error and it's subclasses are unchecked exceptions, which means your code neither has to catch an Errors that could be thrown, nor do you have to declare that you throw those Errors. RunTimeException and its subclasses are also unchecked exceptions, despite their location in the class hierarchy.

Error 及其子类是未经检查的异常,这意味着您的代码既不必捕获可能抛出的错误,也不必声明抛出这些错误。RunTimeException 及其子类也是未经检查的异常,尽管它们位于类层次结构中。

Consider the following code:

考虑以下代码:

void test() {
  int a = 1, b = 0, c = a / b;
}

When run, the above code will produce a java.lang.ArithmeticException. This will compile without any errors, even though an exception is thrown and the code neither catches the ArithmeticException nor declares that it throws this exception. This is the essence of unchecked exceptions.

运行时,上面的代码将生成一个java.lang.ArithmeticException. 即使抛出异常并且代码既不捕获 ArithmeticException 也不声明它抛出此异常,这也将编译而不会出现任何错误。这就是未检查异常的本质。

Consider the location of ArithmeticExceptionin the class hierarchy, especially the fact that this is a subclass of java.lang.Exception. Here you have an exception that derives from java.lang.Exception but because it's also a subclass of java.lang.RuntimeException, it's an unchecked exception so you don't have to catch it.

考虑 的ArithmeticException在类层次结构中的位置,尤其是它是 java.lang.Exception 的子类这一事实。这里有一个派生自 java.lang.Exception 的异常,但因为它也是 java.lang.RuntimeException 的子类,所以它是一个未经检查的异常,因此您不必捕获它。

java.lang.Object
  java.lang.Throwable
    java.lang.Exception
      java.lang.RuntimeException
        java.lang.ArithmeticException

If you want to catch anything that could possibly be thrown, catch a Throwable. However this may not be the safest thing to do because some of those Throwables could be fatal runtime conditions that perhaps should not be caught. Or if you do catch Throwable, you may want to re-throw Throwables that you can't deal with. It depends on the context.

如果你想抓住任何可能被抛出的东西,抓住一个 Throwable。然而,这可能不是最安全的做法,因为其中一些 Throwables 可能是可能不应该被捕获的致命运行时条件。或者,如果您确实捕获了 Throwable,您可能想要重新抛出您无法处理的 Throwable。这取决于上下文。