【发布时间】:2014-01-09 18:52:30
【问题描述】:
我正在开发一个 android 项目,并试图弄清楚如何将异常抛出回调用线程。
我拥有的是一个活动,当用户单击一个按钮时,它会调用另一个 java 类(不是活动,标准类)中的线程函数。标准类中的方法可以抛出IOException 或Exception。我需要将异常对象扔回活动中的调用方法,以便活动可以根据返回的异常做一些事情。
以下是我的活动代码:
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 添加到您的方法声明中。