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 {
}
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 :
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With