johnie walker
johnie walker

Reputation: 27

Java - Getting rid of NullPointerException

Think about two cases case1 and case2 plus two methods method1 and method2. Say method1 solves case1 and method2 solves case2. Now, I have a program that might end up with case1 or case2. In my codes, I call method1 no matter what case happens. But, if case2 occurs, method1 gives a nullpointerexception.

What I want is the following: my codes should call method1 first, if an exception occurs, then method2 is called. How am I gonna do that? Since I have no info about try and catch, I really need some help!

Upvotes: 0

Views: 1458

Answers (2)

Andy Thomas
Andy Thomas

Reputation: 86391

You could do this:

    try {
        method1();
    }
    catch ( Exception e ) {
        method2();
    } 

That said, it's typically better to rely on exceptions only for exceptional conditions. For normal flow of control, you can use an if:

    if ( isCase2() ) {
        method2();
    }
    else {
        method1();
    }

Upvotes: 3

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43098

Catching NullPointerException is a bad pratice - you may catch not the particular exception you want to catch. You have two options:

1) Throw your own exception and catch it later:

  public void method1(Case caze) throws MyException {
    if (case.getType() == CaseType.CaseOne) {
       // processing
    } else {
       throw new MyException("Wrong case type");
    }
  }

And the client code:

try {
   method1(caze);
} catch (MyException e) {
   // log the excpetion
   method2(caze);
}

2) Return a boolean flag, indicating that the processing has been succesfully finished.

Remember, that it is alway better to analyze the values than use try-catch mechanism in your situations. I would suggest variant #2 for you.

Upvotes: 2

Related Questions