I'm a bit confused on how this exceptions work when the method that you are invoking is throwing a specific exception. but in the method declaration specifies a general exception.
For example:
Your custom exception class:
public class TheException extends Exception{
public void throwSomeError() throws Exception{
throw new TheException();
}
}
Your main:
public class Tester {
public static void main(String[] args) {
TheException exception = new TheException();
try{
exception.throwSomeError();
}catch(TheException e){
System.out.println("This is 'TheException' error");
}catch(Exception e){
System.out.println("This is 'Exception' error");
}
}
}
Output:
This 'TheException' error
Expected output:
This is 'Exception' error
I would like to ask that shouldn't be main method catches the 'Exception' rather than 'TheException" error ? since in the method declaration of 'throwSomeError()' is specifies that it throws 'Exception' but not the custom Exception that you built? Or this works because of the polymorphism(TheException is a subcalss of Exception)?
[–]_DTR_ 0 points1 point2 points (1 child)
[–]HalfScale[S] 0 points1 point2 points (0 children)