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

試著忘記壹切 提交于 2019-12-23 16:04:52

问题


If I have a try block that throws a RuntimException subclass, can a subsequent catch block catches it as an Exception? Specifically:

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 RuntimeException extends 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!


回答1:


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

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




回答2:


RuntimeException is derived from Exception, so it will get caught.

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




回答3:


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

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

prints

Caught java.lang.RuntimeException



回答4:


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




回答5:


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.




回答6:


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();
    }
}



回答7:


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....

Rule No.1:

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

Rule No.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.

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.

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.

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.

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....

Just my 2 cents. Anyone experienced the same stuff?

PS: Regarding continous removal of stacktraces:

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...

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)



来源:https://stackoverflow.com/questions/12951236/if-runtimeexception-is-thrown-can-it-be-caught-as-an-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!