简体   繁体   English

Java - 摆脱 NullPointerException

[英]Java - Getting rid of NullPointerException

Think about two cases case1 and case2 plus two methods method1 and method2.考虑两个案例case1和case2加上两个方法method1和method2。 Say method1 solves case1 and method2 solves case2.说method1解决case1,method2解决case2。 Now, I have a program that might end up with case1 or case2.现在,我有一个可能以 case1 或 case2 结尾的程序。 In my codes, I call method1 no matter what case happens.在我的代码中,无论发生什么情况,我都会调用 method1。 But, if case2 occurs, method1 gives a nullpointerexception.但是,如果发生 case2,method1 会给出 nullpointerexception。

What I want is the following: my codes should call method1 first, if an exception occurs, then method2 is called.我想要的是以下内容:我的代码应该首先调用method1,如果发生异常,则调用method2。 How am I gonna do that?我要怎么做? Since I have no info about try and catch, I really need some help!由于我没有关于 try and catch 的信息,我真的需要一些帮助!

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:

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

Catching NullPointerException is a bad pratice - you may catch not the particular exception you want to catch.捕捉NullPointerException是一种不好的做法——您可能无法捕捉到您想要捕捉的特定异常。 You have two options:你有两个选择:

1) Throw your own exception and catch it later: 1)抛出你自己的异常并在以后捕获它:

  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. 2)返回一个boolean标志,表示处理成功。

Remember, that it is alway better to analyze the values than use try-catch mechanism in your situations.请记住,在您的情况下,分析值总是比使用 try-catch 机制更好。 I would suggest variant #2 for you.我会为你推荐变体#2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM