Boa*_*rdy 0 java android exception
我正在开发一个 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
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我的标准类函数
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
}
}
Run Code Online (Sandbox Code Playgroud)
当我放入throw ex
异常时,Eclipse 似乎不高兴,而是要求我将其包围throw ex
在另一个 try/catch 中,这意味着,如果我这样做,则异常将在第二个 try/catch 中处理,而不是调用方法异常处理程序。
感谢您的任何帮助,您可以提供。
改变:
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
}
}
Run Code Online (Sandbox Code Playgroud)
到
private void standardClassFunction() throws Exception
{
String temp = null;
Log.v(TAG, temp.toString()); //This will throw the exception as its null
}
Run Code Online (Sandbox Code Playgroud)
如果要处理调用函数内部被调用函数抛出的异常。你可以通过不抓住它而是像上面那样扔掉它来做到这一点。
此外,如果它是像 NullPointerException 这样的已检查异常,您甚至不需要编写 throws。
有关已检查和未检查异常的更多信息:
http://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
归档时间: |
|
查看次数: |
28404 次 |
最近记录: |