java 当 throw new Error() 写入 try 块时,为什么不执行 catch 块。它只进入 finally 。后面的代码也没有执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25581886/
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-11-02 08:16:15  来源:igfitidea点击:

when throw new Error() is written in try block why catch block is not executed .it go in finally only .Latter code also not executed

javaexception-handling

提问by Rahul Tripathi

Example bellow a program ,where in try block defectedCode() method is called ,So why only output shown only C with "Exception in thread "main" java.lang.Error".

下面是一个程序示例,其中在 try 块中调用了 deffectedCode() 方法,那么为什么只输出显示“线程“main”中的异常 java.lang.Error 仅显示 C。

public class ExceptionTest {

    public static void defectedCode(){

        throw new Error();
    }

    public static void main(String args[]){

        try{
            defectedCode();
            System.out.println("A");

        }catch(Exception e){

            System.out.println("B");

        }finally{

            System.out.println("C");
        }
        System.out.print("D");
    }
}
Exception in thread "main" java.lang.Error

C

at ExceptionTest.defectedCode(ExceptionTest.java:15)

at ExceptionTest.main(ExceptionTest.java:21)

Java Result: 1

回答by Steve Benett

The main reason for this is that you throw an Error but you catch an Exception. If you look at the Throwable hierarchy the point is clear. You can't catch an Error with an Exception. Hence the catch block isn't entered and finally will be called.

造成这种情况的主要原因是您抛出了一个错误,但您捕获了一个异常。如果您查看 Throwable 层次结构,这一点就很清楚了。你不能用异常捕获错误。因此不会输入 catch 块,并且 finally 将被调用。

Try this:

试试这个:

    try{
        defectedCode();
        System.out.println("A");

    }catch(Throwable e){

        System.out.println("B");

    }finally{

        System.out.println("C");
    }

enter image description here

在此处输入图片说明

回答by Dima

Because Erroris not Exception, so the catch block is not monitoring it

因为Error不是Exception,所以 catch 块没有监视它

use throw new Exception()

利用 throw new Exception()

回答by Ritesh Bhakre

You're not supposed to catch errors

你不应该捕捉错误

An Error "indicates serious problems that a reasonable application should not try to catch."

错误“表示合理的应用程序不应试图捕捉的严重问题。”

while

尽管

An Exception "indicates conditions that a reasonable application might want to catch."

异常“表示合理的应用程序可能想要捕获的条件。”

Talking about your code, you're throwing an error and catching an exception, it must be evident by now that they are 2 discrete entities

谈到你的代码,你抛出一个错误并捕获一个异常,现在必须很明显它们是 2 个离散实体

Error along with RuntimeException & their subclasses are unchecked exceptions. All other Exception classes are checked exceptions.

Error 以及 RuntimeException 及其子类是未经检查的异常。所有其他异常类都是检查异常。

Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException, ParseException, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller

检查异常通常是程序可以从中恢复的异常,以编程方式从此类异常中恢复可能是一个好主意。示例包括 FileNotFoundException、ParseException 等。 希望程序员通过使用 try-catch 块来检查这些异常或将其抛回给调用者

On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException, ClassCastException, etc. Many applications will use try-catch or throws clause for RuntimeExceptions & their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.

另一方面,我们有未经检查的异常。如果一切正常,这些异常可能不会发生,但它们确实发生了。示例包括 ArrayIndexOutOfBoundException、ClassCastException 等。许多应用程序将对 RuntimeExceptions 及其子类使用 try-catch 或 throws 子句,但从语言的角度来看,不需要这样做。请注意,从 RuntimeException 中恢复通常是可能的,但设计类/异常的人认为最终程序员没有必要检查此类异常。

Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError, StackOverflowError, etc.

错误也是未经检查的异常,程序员不需要对这些做任何事情。事实上,对错误使用 try-catch 子句是一个坏主意。大多数情况下,从错误中恢复是不可能的,应该允许程序终止。示例包括 OutOfMemoryError、StackOverflowError 等。

Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions(also unchecked exceptions) in code. Checked exceptions should be handled by the code.

请注意,虽然 Errors 是未经检查的异常,但我们不应该尝试处理它们,但是在代码中处理 RuntimeExceptions(也是未经检查的异常)是可以的。检查的异常应该由代码处理。

回答by Karthikeyan

Though ethically you should not catch an error, you can still catch that as a Throwable Object.

尽管从道德上讲,您不应捕获错误,但您仍然可以将其作为 Throwable Object 捕获。

回答by J4v4

An Erroris not an Exception.

AnError不是Exception

The base class for throwable objects is Throwable.
Errors and exceptions are two different types of throwables. However, errors are usually not supposed to be caught, which is why people use catch(Exception e)to catch basically all exceptions that they should catch.

可抛出对象的基类是Throwable.
错误和异常是两种不同类型的 throwable。然而,错误通常不应该被捕获,这就是为什么人们catch(Exception e)习惯于捕获基本上所有他们应该捕获的异常。

Obviously, since Erroris not a subclass of Exception, it's not affected by catch(Exception e), so it's not caught. finallyis always executed, regardless of whether the throwable has been caught or not.

显然,由于Error不是 的子类Exception,因此不受 影响catch(Exception e),因此不会被捕获。finally总是被执行,不管 throwable 是否被捕获。