user755806
user755806

Reputation: 6825

Catching run time exceptions?

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!

Upvotes: 2

Views: 137

Answers (2)

Deepak
Deepak

Reputation: 2905

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.

Upvotes: 5

Aniket Thakur
Aniket Thakur

Reputation: 69005

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.

Upvotes: 10

Related Questions