Android - 如果我尝试一个函数,我会捕获NullPointerExceptions吗?

时间:2015-12-30 02:00:22

标签: android nullpointerexception try-catch

我可以这样做:

 try {
        loadItem();
    } catch (NullPointerException e) {
        Toast.makeText(getActivity(),"Sorry, we couldn't load that item. Please try again",Toast.LENGTH_SHORT).show();
    }

捕获loadItem()中可能出现的任何NullPointerExceptions?

1 个答案:

答案 0 :(得分:2)

是。除非loadItem()本身在没有重新抛出的情况下捕获异常,否则它将冒泡到调用者。

您可以使用以下程序对此进行测试,该程序由于异常处理程序的原因而输出Ouch!

public class DodgyProg {
    public static void loadItem() {
        throw new NullPointerException();
    }
    public static void main(String []args){
        try {
            loadItem();
        } catch (NullPointerException e) {
            System.out.println("Ouch!");
        }
    }
}