Java android-处理异常以更新UI

Java android-处理异常以更新UI,java,android,exception,kotlin,try-catch,Java,Android,Exception,Kotlin,Try Catch,在我的申请中,我想: 在片段中有一个方法a 在方法A中,调用用`@Throws(IOException::class)注释的方法B` 在方法B中,调用具有“try catch”的方法C,并在“catch”处抛出IOException(e)` 在方法A中接收错误并使用信息执行操作 到目前为止,我已经: fun methodA() { methodB() //Get exception and do stuff } @Throws(IOException::class) f

在我的申请中,我想:

  • 在片段中有一个方法a
  • 在方法A中,调用用`@Throws(IOException::class)注释的方法B`
  • 在方法B中,调用具有“try catch”的方法C,并在“catch”处抛出IOException(e)`
  • 在方法A中接收错误并使用信息执行操作
到目前为止,我已经:

fun methodA() {
    methodB()
    //Get exception and do stuff
}

@Throws(IOException::class)  
fun methodB() {
    methodC()
}  

fun methodC() {
    try {
        //Something that can throw exception
    } catch (e: IOException) {
        throw IOException(e)
    }
}
这是正确的方法还是例外的方法?但是,我怎样才能知道异常是在方法a中抛出的呢?我在想这样的事情:

fun methodA() {
    try {
        methodB()
    } catch (e: IOException) {
        //received exception thrown by method C and do stuff
    }
}
我能用它实现我想要的吗?如果没有,你能帮我吗?
谢谢

如果您使用第二版本的
methodA()
,您的代码应该可以正常工作。但是为什么在
methodC()
中捕获异常,却抛出一个新副本?相反,考虑以下内容:

fun methodA() {
    try {
        methodB()
    } catch (e: IOException) {
        // error flow
    }
}

@Throws(IOException::class)
fun methodB() {
    methodC()
}

@Throws(IOException::class)
fun methodC() {
    // do something that can throw exception
}
IOException
向上传播到
methodA()
,您可以在那里处理它

您也可以考虑在调用堆栈中更深地捕获异常:

fun methodA() {
    val err = methodB()
    if (err) {
        // error flow
    } else {
        // normal flow
    }
}

fun methodB(): Boolean {
    return methodC()
}

fun methodC(): Boolean {
    return try {
        // do something that can throw exception
        false
    } catch (e: IOException) {
        true
    }
}
现在,您应该使用这两种方法中的哪一种?这取决于您的实际代码。这是一场讨论


(您给出的代码的另一个问题是,
methodB()
是多余的。但我假设它在您的实际程序中做了一些有趣的事情。)

没有必要使用methodC中的try-catch来抛出异常,如果您希望您的函数先抛出一个异常注释,然后在其中抛出您的异常,如果另一个函数调用该函数,它必须处理该异常或抛出该异常,因为该异常是在
methodC()
中生成的,并传播到
methodA
,因此必须对
methodC()
methodB()
进行注释以抛出所需的异常,将异常抛出到
methodC()
中,它将通过
methodB()
传播,然后使用
methodA()
中的try-catch来处理异常