[java] Why doesn't catching Exception catch RuntimeException?

This is very odd to me. RuntimeException inherits from Exception, which inherits from Throwable.

catch(Exception exc) { /* won't catch RuntimeException */

but

catch(Throwable exc) { /* will catch RuntimeException */

I know RuntimeException is special in that it's unchecked. But to my understanding that applies just to whether exceptions have to be declared, not whether they are caught. And even then, I don't know why this logic would break on catching Throwable.

This is pretty relevant to me since I have a situation where RuntimeException can be thrown in a terminal operation. I'm not sure the name for this pattern, but something like, my class EmailRoller takes an array of Callbacks. The code looks like this:

for(Callback cb : callbacks) {
    try {
        cb.call(item);
    }
    catch(Exception exc) {
        logger.error("Error in callback: ", exc);
   }
}

So this is a case where something like an OOME needs to fly through, because if one of these callbacks consumes all machine memory, that sure as heck is going to affect the running of the other ones. But a NullPointerException? Or an IndexOutOfBoundsException? Those will affect the callback but won't prevent the others from running.

Also, this is a bit of an enterprise design. Different programmers or teams can add callbacks to process the item, but they should be isolated from each other. This means, as the programmer responsible for insulating these callbacks from each other, I shouldn't rely on them to make sure errors don't slip through. Catching Exception should be about the right line, but it isn't because RuntimeException slips through. So my more general question is: what's a good pattern here? Just catch(Exception | RuntimeException exc), which I believe is a syntax error because of the inheritance?

This question is related to java exception runtimeexception

The answer is


Catching Exception will catch a RuntimeException


I faced similar scenario. It was happening because classA's initilization was dependent on classB's initialization. When classB's static block faced runtime exception, classB was not initialized. Because of this, classB did not throw any exception and classA's initialization failed too.

class A{//this class will never be initialized because class B won't intialize
  static{
    try{
      classB.someStaticMethod();
    }catch(Exception e){
      sysout("This comment will never be printed");
    }
 }
}

class B{//this class will never be initialized
 static{
    int i = 1/0;//throw run time exception 
 }

 public static void someStaticMethod(){}
}

And yes...catching Exception will catch run time exceptions as well.


class Test extends Thread
{
    public void run(){  
        try{  
            Thread.sleep(10000);  
        }catch(InterruptedException e){  
            System.out.println("test1");
            throw new RuntimeException("Thread interrupted..."+e);  
        }  

    }  

    public static void main(String args[]){  
        Test t1=new Test1();  
        t1.start();  
        try{  
            t1.interrupt();  
        }catch(Exception e){
            System.out.println("test2");
            System.out.println("Exception handled "+e);
        }  

    }  
}

Its output doesn't contain test2 , so its not handling runtime exception. @jon skeet, @Jan Zyka


catch (Exception ex) { ... }

WILL catch RuntimeException.

Whatever you put in catch block will be caught as well as the subclasses of it.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to exception

Connection Java-MySql : Public Key Retrieval is not allowed How to print an exception in Python 3? ASP.NET Core Web API exception handling Catching FULL exception message How to get exception message in Python properly What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? Argument Exception "Item with Same Key has already been added" The given key was not present in the dictionary. Which key? sql try/catch rollback/commit - preventing erroneous commit after rollback

Examples related to runtimeexception

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file Why doesn't catching Exception catch RuntimeException? ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat NameError: global name 'xrange' is not defined in Python 3 Unable instantiate android.gms.maps.MapFragment Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'? Android 'Unable to add window -- token null is not for an application' exception Understanding checked vs unchecked exceptions in Java Can't create handler inside thread which has not called Looper.prepare()