Java 正在将异常发回调用方法

Java 正在将异常发回调用方法,java,android,exception,Java,Android,Exception,我正在从事一个android项目,我正试图找出如何将异常抛出回调用线程 我拥有的是一个活动,当用户单击一个按钮时,它调用另一个java类中的线程函数,而不是活动,标准类。标准类中的方法可以引发IOException或异常。我需要将异常对象抛出回活动中的调用方法,以便活动可以根据异常返回的内容执行一些操作 以下是我的活动代码: private void myActivityMethod() { try { MyStandardClass myClass = new

我正在从事一个android项目,我正试图找出如何将异常抛出回调用线程

我拥有的是一个活动,当用户单击一个按钮时,它调用另一个java类中的线程函数,而不是活动,标准类。标准类中的方法可以引发IOException或异常。我需要将异常对象抛出回活动中的调用方法,以便活动可以根据异常返回的内容执行一些操作

以下是我的活动代码:

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中,这意味着,如果我这样做,那么异常将在第二个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
    }
}

如果要在调用函数内部处理被调用函数中引发的异常。你可以不去抓它,而是像上面那样扔它

此外,如果它是一个选中的异常,比如NullPointerException,则您甚至不需要编写抛出

有关已检查和未检查异常的详细信息:


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


因此,当您从另一个类调用该方法时,将要求您在try/catch中继续调用。

异常是选中的异常。NullPointerException也是一个异常,但更具体地说,它是一个未经检查的RuntimeException。非常标准的java内容…只需将抛出添加到方法声明中。在这种情况下,抛出是不必要的。是的。但是如果在他的方法中有一些未经检查的异常,他需要这样做。我举了一个例子,在这种情况下,请添加一个省略号或注释来解释。
private void standardClassFunction() throws Exception 
{

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

}