Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtim Exception extends Exception and Custom Exception extends from Exception Why the later one is compile time exception and other is not?

In Java I have a Exception class that extends from Exception, But whenever I throw it, the compiler says that it needs to be caught/ must declare that methods throws Exception.

When I use a RuntimeException that extends from Exception, the compiler does not stop, It takes them as Runtime Exception and we need not handle it.

Is there a way where I can make a MyException extend from Exception and still have it as runtime exception.? or What makes this as possibility in class RuntimeException

private void compileTime() throws MyException{
        throw new MyException();
    }

    private void runTime() {
        throw new MyRuntimeException();
    }

    class MyException extends Exception {

    }
    class MyRuntimeException extends RuntimeException {

    }
like image 781
Ganesh Avatar asked Jan 21 '13 09:01

Ganesh


3 Answers

RuntimeException are a subset of unchecked exceptions for exceptions from which recovery is possible.

unchecked exceptions are not checked at compile-time which means that the compiler doesn't require methods to catch or to specify (with a throws) them.

The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes.

Please check the Exception Hierarchy through this image : exception hierarchy

In short, Any exception that derives from "Exception" is a checked exception, whereas a class that derives from RuntimeException is un-checked. RuntimeExceptions do not need to be explicitly handled by the calling code.

like image 183
Rahul Avatar answered Nov 15 '22 00:11

Rahul


No way. According to specifications, only exceptions extended from RuntimeException class or Error class are considered as unchecked exceptions (JLS 7, p. 11.1.1).

like image 45
Andremoniy Avatar answered Nov 15 '22 00:11

Andremoniy


What you are calling a "compile-time" exception is known as a Checked exception. As you say the compiler will require you to include it in your method signature and your callers will need to handle the possibility that it may be thrown.

RuntimeException is explicitly intended for the "unchecked" exception case.

From the docs

A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

So just extend RuntimeException if you want an unchecked excption.

like image 23
djna Avatar answered Nov 14 '22 22:11

djna