public class WhatTheShoot {
public static void main(String args[]){
try {
throw null;
} } catch (Exception e){
System.out.println(e instanceof NullPointerException);
System.out.println(e instanceof FileNotFoundException);
}
}
}
Run the code above
true
false
That's the result. I thought there would be a compilation error, but it was amazing that it was compiled well. Why can you throw null as an exception in Java? And why is it cast as NullPointerException?
java exception-handling nullpointerexception
Null appears to be treated as NullPointerException, but it is not. The reason why null appears to be cast as NullPointerException is because This is because the code itself, throw null, calls the result of throwing the nullPointerException.
In other words, throw is to check if the factor is not null and then torow the nullPointerException when it is null.
© 2024 OneMinuteCode. All rights reserved.