Alex Rivera | Logout

Is catch block able to catch Throwable (both error and exception)

Asked 2011-07-21T06:41:49.703
11

In one of my interview, they asked me, is it possible to write Throwable in catch() like this

try{
some code
}
catch(Throwable t)
{
}

I said yes. it will not give a compile time error but jvm would not handle it if there occur an Error(sub class of Throwable ), since Errors are irreversible conditions that can not be handled by jvm. than they further asked than what is the use of writing Throwable .

Please give me proper reply can we use Throwable in catch. if yes why.

Edit
Report

1 Answer

0

Catching Throwable will catch all Exceptions (including RuntimeExceptions) and all Errors. It is not recommended to catch any of the parent Throwables (Throwable, Error, Exception or RuntimeException) but it is not uncommon to find this if a method throws too many checked exceptions or throws Exception.

It is not uncommon in certain APIs to document a method as throws Exception. This provides some flexibility at the expense of control. I like to define a new Exception class to handle this sort of case but that is personal preference.

The following simple class shows samples of the throwable types and corresponding catch blocks.

public class ThrowableExamples {

    public static void main(String[] args) {
        try {
//          throw new NoSuchMethodException("Exception");
//          throw new Exception("Exception");
//          throw new IllegalStateException("RuntimeException");
//          throw new RuntimeException("RuntimeException");
            throw new NoSuchMethodError("Error");
//          throw new Error("Error");
//          throw new Throwable("Throwable");

        } catch (RuntimeException e) {
            System.out.println("Caught RuntimeException: " +  (e.getMessage().equals("RuntimeException") ? "Expected" : "Unexpected"));

        } catch (Exception e) {
            System.out.println("Caught Exception: " +  (e.getMessage().equals("Exception") ? "Expected" : "Unexpected"));

        } catch (Error e) {
            System.out.println("Caught Error: " +  (e.getMessage().equals("Error") ? "Expected" : "Unexpected"));

        } catch (Throwable e) {
            System.out.println("Caught Throwable: " +  (e.getMessage().equals("Throwable") ? "Expected" : "Unexpected"));
        }
    }
}
answered 2011-07-21T08:22:14.087

Your Answer