2

I know that RunTimeExceptions can be caught by Exception catch block as below.

public class Test { public static void main(String[] args) { try { throw new RuntimeException("Bang"); } catch (Exception e) { System.out.println("I caught: " + e); } } } 

I have my own created exception class as below.

public class CustomException extends Exception { public CustomException(String message, Throwable cause) { super(message, cause); } public CustomException(String message) { super(message); } } 

But now instead of keeping Exception in catch block, i kept CustomException.But run time exception is not caught by catch block now. Why?

public class Test { public static void main(String[] args) { try { //consider here i have some logic and there is possibility that the logic might throw either runtime exception or Custom Exception throw new RuntimeException("Bang"); } catch (CustomException e) { System.out.println("I caught: " + e); } } } 

Thanks!

1
  • no need to write java again in title, java tag is sufficient Commented Dec 18, 2013 at 5:29

2 Answers 2

10

enter image description here

Extending Exception class does not make it is Runtime Exception. See above diagram. Also you can use polymorphic reference(superclass) to catch an subclass Exception. It does not work the other way around.

Sign up to request clarification or add additional context in comments.

2 Comments

As they say A picture paints a thousand words
RuntimeException is not a catch-all, an Exception is, or maybe a Throwable but all three are concrete classes and don't provide a 'catch-all' interface.
5

This is because CustomException is not a super class of RuntimeException. Because you are throwing RuntimeException, which is not the subclass of CustomException, the catch block is not catching it.

1 Comment

Aye, 755806 but CustomException does not extend RuntimeException, they have different contracts.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.