java 如果抛出 RuntimeException,是否可以将其作为 Exception 捕获?

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

If RuntimeException is thrown, can it be caught as an Exception?

javaexception

提问by IAmYourFaja

If I have a tryblock that throws a RuntimExceptionsubclass, can a subsequent catchblock catches it as an Exception? Specifically:

如果我有一个try抛出RuntimException子类的块,后续catch块是否可以将它作为Exception? 具体来说:

public class MyAppException extends RuntimeException {
    // ....
}

// In some other part of the code:
try {
    // Executing this results with doSomething() throwing a MyAppException.
    int x = doSomething();
} catch(Exception exc) {
    // Does the thrown MyAppException get caught here?
}

My thinking is yes, because a RuntimeExceptionextends Exception. However I have some production code that is not behaving this way. So obviously, if the answer is no, then that's my answer; otherwise I need to dig down and see why my code is breaking bad. Thanks in advance!

我的想法是肯定的,因为 a RuntimeExceptionextends Exception。但是,我有一些不以这种方式运行的生产代码。很明显,如果答案是否定的,那么这就是我的答案;否则我需要深入挖掘,看看为什么我的代码很糟糕。提前致谢!

回答by Tudor

RuntimeExceptionis derived from Exception, so it will get caught.

RuntimeException派生自Exception,因此它会被捕获。

Having said this, don't do it! Runtime exceptions should be prevented, not caught.

说了这么多,千万别做!运行时异常应该被阻止,而不是被捕获。

回答by Subhrajyoti Majumder

Yes. It will catch RuntimeExceptionbut in case any Exceptionarise in catch block that you have to catch again.

是的。它将捕获,RuntimeExceptionException如果在 catch 块中出现任何您必须再次捕获的情况。

I would suggest you to make a local deployment and debug the code.

我建议您进行本地部署并调试代码。

回答by Peter Lawrey

If catch(Exception) is not catching your RuntimeException then your application is not behaving the way you think.

如果 catch(Exception) 没有捕捉到您的 RuntimeException,那么您的应用程序就没有按照您的想法运行。

try {
    throw new RuntimeException();
} catch (Exception e) {
    System.out.println("Caught "+e);
}

prints

印刷

Caught java.lang.RuntimeException

回答by raj

Yes , you can catch RuntimeException...But i think its not a good approach, if you catch it you should properly manage it. Otherwise the result is out of your hand. Best way is to leave it to JVM . JVM will handle it.

是的,您可以捕获 RuntimeException...但我认为这不是一个好方法,如果您捕获它,您应该正确管理它。否则结果是你无法控制的。最好的方法是将它留给 JVM 。JVM 会处理它。

回答by BartoszMiller

Yes. It is possible to catch RuntimeExceptions. All subclasses of Throwable can be caught.

是的。可以捕获 RuntimeExceptions。Throwable 的所有子类都可以被捕获。

回答by feikiss

Yes, your thinking is correct, I think the best way to know answer to "just writing the code", let the code tell you the answer. you can see the following simple example code:

是的,你的想法是正确的,我认为最好的答案是“只写代码”,让代码告诉你答案。您可以看到以下简单的示例代码:

    package own;

public class MyExceptionTest {

    public void testRuntimeException (){
        throw new MyException();
    }

    public static void main(String[] args) {
        try{
            new MyExceptionTest().testRuntimeException();
        }catch(Exception e){
            System.out.println(e.getClass().getName());
        }
    }
}    

class MyException extends RuntimeException{
    public MyException(){
        super();
    }
}

回答by KyDay

I am a project manager in IT and I have had the same argument over and over with my devs and they simply dont care. Browsing the net, even most people advocate catching and throwing RuntimException... Every time I see it I get unbelievably furious about the inaptitude after 10 years of experience....

我是 IT 领域的项目经理,我和我的开发人员一遍又一遍地争论同样的问题,他们根本不在乎。网上浏览,连大多数人都提倡抓和抛出RuntimException……每次看到我都对10年经验的无能感到难以置信的愤怒……

Rule No.1:

规则一:

Never ever throw a runtimeexception in Program if you didnt catch a RuntimeException.

如果您没有捕获 RuntimeException,永远不要在 Program 中抛出 runtimeexception。

Rule No.2:

规则 2:

Only catch a Runtimeexception in order to some really import stuff that has nothing to do with your software: e.g. send a mail to operations emergency shift, log exception, restart the server....

仅捕获运行时异常才能真正导入与您的软件无关的内容:例如,向操作紧急转移、记录异常、重新启动服务器...发送邮件。

The reason for this is that in good software there is no stacktrace in a logfile. When feel uncomfortable starting to code do this:

这样做的原因是在好的软件中,日志文件中没有堆栈跟踪。当开始编码感到不舒服时,请执行以下操作:

Create new class DevelopmentException Extends Exception. Then goahead and write your code and catch for exception initially. Then you rethrow it as your very own developmentexception. In the method catching it you log it.

创建新类 DevelopmentException 扩展异常。然后继续编写代码并最初捕获异常。然后你将它作为你自己的开发异常重新抛出。在捕获它的方法中,您将其记录下来。

Now: Everyday grep for your very personal DevelopmentException. If you find one this means there is still work to do. Go into your code and see where the Exception came from and catch it beforehand.

现在:每天 grep 为您非常个人的 DevelopmentException。如果你找到了,这意味着还有工作要做。进入您的代码并查看异常来自何处并事先捕获它。

Ideally you will never see a DevelopmentException in this part of your program again. Repeat until there are 0 Stacktraces in your Software left and you have perfected Exception handling.

理想情况下,您再也不会在程序的这一部分看到 DevelopmentException。重复直到您的软件中剩下 0 个堆栈跟踪并且您已经完善了异常处理。

The biggest issue with throwing and catching runtime exception is that the compile ignores it. So this means when one of your colleagues writes a booking interface and throws RuntimeException when there is a value missing (yeah, ppl really do)... ...the compiler will not show you that there might be a runtimeexception. Now, when you dont catch it then your program might just shut down without any logging.

抛出和捕获运行时异常的最大问题是编译会忽略它。因此,这意味着当您的一位同事编写预订界面并在缺少值时抛出 RuntimeException(是的,ppl 确实如此)... ...编译器不会向您显示可能存在运行时异常。现在,当您没有捕获它时,您的程序可能会在没有任何日志记录的情况下关闭。

Why is it called RuntimeException? Many mistake this for Error during Runtime of Program, however it actually means 'An Exception so utterly destructive that the Java Runtime Environment need to be stoppep'. In other words it meand: OutOfMemory, BrokenRam, FaultyImplementation of JRE, etc... basically stuff that tell you: Program cannot run because PC is crashing....

为什么叫 RuntimeException?许多人将其误认为是程序运行时出错,但它实际上意味着“异常具有破坏性,Java 运行时环境需要停止运行”。换句话说,它的意思是:OutOfMemory、BrokenRam、JRE 的 FaultyImplementation 等……基本上是告诉你:程序无法运行,因为 PC 崩溃了……

Just my 2 cents. Anyone experienced the same stuff?

只有我的 2 美分。有人经历过同样的事情吗?

PS:Regarding continous removal of stacktraces:

PS:关于不断删除堆栈跟踪:

Once you see an exception try to catch it with e.g. NullpointerException. When you see Nullpointerexception go to your code and remove the stacktrace, and just log.WARN(NullpointerOccured) and write your Program to retry or so...

一旦您看到异常,请尝试使用例如 NullpointerException 来捕获它。当您看到 Nullpointerexception 时,请转到您的代码并删除堆栈跟踪,然后只需 log.WARN(NullpointerOccured) 并编写您的程序以重试左右......

Ideally you repeat until you never see a Stacktrace again. When you cannot see a stacktrace ever it means all that could possibly go wrong is taken care of(Except for RuntimeException of course)

理想情况下,您可以重复此操作,直到您再也看不到 Stacktrace 为止。当您永远看不到堆栈跟踪时,这意味着所有可能出错的地方都已解决(当然 RuntimeException 除外)