Reputation: 7980
I'm using Netbeans 8 IDE
and I just came to this odd situation. Let's say I've a method in a class that throws
and Exception
and when I call that method Netbeans
does not enforce the try catch
. Sometimes an Exception
may occur and it is not catch.
Why isn't Netbeans enforcing the try catch
method?
Here's an example:
public class MyMethodClass {
public MyMethodClass() {}
public void someMethod() throws NullPointerException {
// do something
if(something == null) {
throw new NullPointerException();
}
// do something else
}
}
public class MyClass {
public MyClass() {
MyMethodClass mmc = new MyMethodClass();
// Here Netbeans does not force me to use a try catch, why?
mmc.someMethod();
}
}
Upvotes: 1
Views: 1425
Reputation: 5046
NullPointerException
is an unchecked exception, which means that you don't always need to catch it. Unchecked exceptions are those which extend RuntimeException
or Error
. The main purpose of these is for cases where there usually is no recovery; methods aren't required to declare unchecked exceptions either. This is perfectly valid:
public void throwNPE() {
throw new NullPointerException();
}
Here is one of Oracle's statements on checked vs unchecked exceptions.
Upvotes: 3
Reputation: 393791
NullPointerException
is an unchecked exception (since it's a subclass of RuntimeException
). You don't have to catch unchecked exceptions for the code to compile.
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary
Upvotes: 3