Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java try..catch VS long if()_Java_If Statement_Nullpointerexception - Fatal编程技术网

Java try..catch VS long if()

Java try..catch VS long if(),java,if-statement,nullpointerexception,Java,If Statement,Nullpointerexception,我的项目中有一个复杂的模型结构。 有时我不得不从中获得一个深层次的价值。如下所示: something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething(); SomethingFourth fourth = null; try { fourth = something.getSomethongElse().getSecondSomething().getThirdSometh

我的项目中有一个复杂的模型结构。
有时我不得不从中获得一个深层次的价值。如下所示:

something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
SomethingFourth fourth = null;

try {
    fourth = something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
} catch (NullPointerException e) { }

if(fourth != null) {
    ///work with fourth
}
问题是,这些方法中的每一个都可能返回
null
,如果返回,我将得到
NullPointerException

我想知道的是,如果我喜欢的话,我应该写长一点吗

if(something != null && something.getSomethongElse() != null && something..getSomethongElse().getSecondSomething() != null && something.getSomethongElse().getSecondSomething().getThirdSomething() != null && omething.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething() != null) {
    //process getFourthSomething result.
}
或者只需使用try..catch即可,如下所示:

something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
SomethingFourth fourth = null;

try {
    fourth = something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
} catch (NullPointerException e) { }

if(fourth != null) {
    ///work with fourth
}

我知道
NPE
是一件需要避免的事情,但是在我的例子中避免它不是一件开销吗?

如果您可以重构代码并使每个方法返回
可选的
。可以避免空检查并尝试。。。接住

Optional<Result> result = something.getSomethingElse()
.flatMap(e -> e.getSecondSomething())
.flatMap(x -> x.getThirdSomething())
.flatMap(e -> e.getFourthSomething());
// at the end to check if result is present
result.ifPresent(..some_logic_here..); // or result.orElse(...);

@shmosel,你说得对,谢谢!光学的?您的意思必须是可选的,但要详细得多。@user6788933,非常感谢您发现输入错误,我将更新我的答案。我同意其他题目的答案更详细。然而,我的目标只是展示如何在这个特殊的情况下使用Optional。