Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

exception

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!

like image 650
IAmYourFaja Avatar asked Nov 27 '22 17:11

IAmYourFaja


2 Answers

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

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

like image 70
Tudor Avatar answered Dec 21 '22 17:12

Tudor


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.

like image 44
Subhrajyoti Majumder Avatar answered Dec 21 '22 18:12

Subhrajyoti Majumder