处理来自Throwable catch的NullPointerException的最佳方法是什么? (机器人)

时间:2014-07-28 13:53:16

标签: java android nullpointerexception jit throwable

处理来自Throwable catch的NullPointerException的最佳方法是什么。

public void run() {
    try{

    }catch (Throwable e){

        // e.getMessage() is equal to null 
        // and sends a NullPointerException
        if (e.getMessage().equals(“something“){

        }
    }
}

进行一些研究我发现here JIT编译器会在某些例外情况下优化掉堆栈跟踪

我以为我可以在Throwable catch中抛出一个Exception,但看起来并不干净。

谢谢!

1 个答案:

答案 0 :(得分:2)

不要编写可能抛出NullPointerException的代码。

public void run() {
    try {

    } catch (Throwable e){

        if (“something“.equals(e.getMessage()) {

        }
    }
}

public void run() {
    try {

    } catch (Throwable e){

        if (e.getMessage() != null && e.getMessage().equals(“something“) {

        }
    }
}