I am new to Java and trying to understand Exceptions in Java.
class MyException extends Exception {
void someMethod () {
doStuff();
}
void doStuff() throws MyException {
try {
throw new MyException();
}
catch(MyException me) {
throw me;
}
}
}
This Program gives the error:
java:3: unreported exception MyException; must be caught or declared to be thrown
doStuff(); ^
The try and catch block are written within the doStuff() method. Also the doStuff() method “throws” MyException, then why do need to throw MyException in someMethod() also?
You did indeed catch MyException, but you re-threw it, so a new, active exception needs to be caught.
This is called a checked exception. Anytime you call the doStuff() method, you need to wrap it in a try/catch for MyException OR you can declare that your method will also throw MyException.
This guarantees that known exceptions will be at least thought about in the coding process.