【问题标题】:Android - If I try a function, will I catch NullPointerExceptions?Android - 如果我尝试一个函数,我会捕获 NullPointerExceptions 吗?
【发布时间】:2015-12-30 02:00:21
【问题描述】:

我可以这样做吗:

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

并捕获可能在 loadItem() 中发生的任何 NullPointerExceptions?

【问题讨论】:

  • 是的,你可以这样做。为什么不通过在该方法中抛出 NullPointerException 来自己测试呢?
  • 你可以在问这里之前尝试一下

标签: android nullpointerexception try-catch


【解决方案1】:

是的。除非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!");
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 2017-05-17
    • 1970-01-01
    相关资源
    最近更新 更多