【问题标题】:Throwing Exception back to the calling method将异常抛出回调用方法
【发布时间】:2014-01-09 18:52:30
【问题描述】:

我正在开发一个 android 项目,并试图弄清楚如何将异常抛出回调用线程。

我拥有的是一个活动,当用户单击一个按钮时,它会调用另一个 java 类(不是活动,标准类)中的线程函数。标准类中的方法可以抛出IOExceptionException。我需要将异常对象扔回活动中的调用方法,以便活动可以根据返回的异常做一些事情。

以下是我的活动代码:

private void myActivityMethod()
{
    try
    {
        MyStandardClass myClass = new MyStandardClass();
        myClass.standardClassFunction();
    }
    catch (Exception ex)
    {
        Log.v(TAG, ex.toString());
        //Do some other stuff with the exception
    }
}

下面是我的标准类函数

private void standardClassFunction()
{
    try
    {
        String temp = null;
        Log.v(TAG, temp.toString()); //This will throw the exception as its null
    }
    catch (Exception ex)
    {
        throw ex; //Don't handle the exception, throw the exception backto the calling method
    }
}

当我将 throw ex 放入异常时,Eclipse 似乎不高兴,而是要求我将 throw ex 包围在另一个 try/catch 中,这意味着,如果我这样做,异常将在内部处理第二个尝试/捕获不是调用方法异常处理程序。

感谢您提供的任何帮助。

【问题讨论】:

  • Exception 是一个检查异常。 NullPointerException 也是一个 Exception,但更具体地说是一个未选中的 RuntimeException
  • 相当标准的 java 东西...只需将 Throws 添加到您的方法声明中。

标签: java android exception


【解决方案1】:

变化:

private void standardClassFunction()
{
    try
    {
        String temp = null;
        Log.v(TAG, temp.toString()); //This will throw the exception as its null
    }
    catch (Exception ex)
    {
        throw ex; //Don't handle the exception, throw the exception backto the calling method
    }
}

private void standardClassFunction() throws Exception 
{

        String temp = null;
        Log.v(TAG, temp.toString()); //This will throw the exception as its null

}

如果你想在调用函数内部处理被调用函数抛出的异常。你可以像上面那样不抓住它,而是扔掉它。

如果它是像 NullPointerException 这样的检查异常,你甚至不需要编写 throws。

更多关于检查和未检查的异常:

http://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/

【讨论】:

  • 在这种情况下,throws 是不必要的。
  • 是的。但如果他的方法中有一些未经检查的异常,他需要这样做。我举个例子
  • 在这种情况下,请添加省略号或注释说明。
【解决方案2】:

如上所述,当你在方法签名中声明 throws 时,编译器就知道该方法可能会抛出异常。

所以现在当您从其他类调用该方法时,系统会要求您在 try/catch 中覆盖您的调用。

【讨论】:

    猜你喜欢
    • 2012-11-22
    • 2017-05-31
    • 2016-07-10
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    相关资源
    最近更新 更多