开发者

Java - Getting rid of NullPointerException

开发者 https://www.devze.com 2023-03-08 10:42 出处:网络
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 case

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!


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();
    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消