有没有办法通过这种方式处理nullpointer异常?

dri*_*ter 3 java android

是否有意义通过这样的方式处理空指针异常

private void doWork(Object object) {
    if (object == null) {
        try {
            throw new IllegalArgumentException();
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 10

不,这没有多大意义.

不要抓住异常.做就是了

if (object == null)
    throw new IllegalArgumentException("Argument object may not equal null");
Run Code Online (Sandbox Code Playgroud)

根据您的建议,该方法将文档为

做一些有争议的工作object.如果objectnull它打印在标准输出一些垃圾,没有别的.


作为旁注,既然您还在学习Java,那么您的try-catch块:

try {
    throw new IllegalArgumentException();
} catch (Exception e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

......相当于......

new IllegalArgumentException().printStackTrace();
Run Code Online (Sandbox Code Playgroud)