I usually check for null before calling a method, if there's a chance the variable could be null. So:
if (myPrg != null) {
myPrg.test1();
myPrg.test2();
} else {
// do something else instead if needed
}
I typically use this first approach when I wouldn't need to do anything, or would need to do something completely different if the object were null.
Or set myPrg to something non-null if it's null, before calling the test methods:
if (myPrg == null) {
myPrg = new MyProgram();
}
myPrg.test1();
myPrg.test2();
I typically use this second method for cases where the object may be null because it has not been initialized yet, and if that's the case, I want to initialize it, and then execute the code as usual.
Alternately, you can use try/catch:
try {
myPrg.test1();
muPrg.test2();
} catch(NullPointerException e) {
// do something else instead
}
try/catch is not usually done for NullPointerException. It's better programming practice to use one of the other methods above.
by the way if you do any of these things, you can take out the throws NullPointerException
clause, since there won't be anything to cause it to throw the exception anymore.
Note that you can't call a method on a null object. This is in part because a null object doesn't know what type it is (so it doesn't know it's a null object of type MyProgram) and also because typically the methods on a class require some context from the object, which is why they were written as methods on the class.
If you have methods that don't require an object to act on, make them static.
public static void test1() {
System.out.println("say hello");
}
Can be called without needing an instance of MyProgram to call it on. You could just call MyProgram.test1();
I think that may be what you're looking for rather than a way to handle a NullPointerException