I get an unhandled Exception type error for the following code, even though, as I understand it, I have handled the exception in the catch block.
class NewException extends Exception{
private String msg;
public NewException(String msg){
this.msg = msg;
}
public String getExceptionMsg(){
return msg;
}}
class CatchException {
public static void method () throws NewException{
try {
throw new NewException("New exception thrown");
}
catch (NewException e){
e.printStackTrace();
System.out.println(e.getExceptionMsg());
}
finally {
System.out.println("In finally");
}
}}
public class TestExceptions{
public static void main(String[] args){
CatchException.method();
}}
Your
method()declares that it throwsNewException. Whatever is inside that method is irrelevant:The compiler sees that you are calling
CatchException.method()inmain()and that you are not handling it in any way (either catching or declaringmain()to throwNewExceptionas well. Thus the error.The compiler doesn’t care if you are actually throwing that exception or not. Have a look at
ByteArrayInputStream.close()– there is no way it’ll ever throw anIOException– but you still have to handle it since it’s declared.