java - android - 处理异常以更新 UI

标签 java android exception kotlin try-catch

在我的申请中,我想:

  • 在 fragment 中有一个方法 A
  • 在方法 A 中,调用一个用 `@Throws(IOException::class)` 注释的方法 B
  • 在方法 B 中,调用方法 C,它有一个 `try catch`,在 `catch` 处它`throw 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)
    }
}

这是正确的方式还是异常(exception)的方式?但是,我如何才能知道在方法 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
    }
}

现在,您应该使用这两种方法中的哪一种?这取决于您的实际代码。 Here是一个讨论。

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

关于java - android - 处理异常以更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48045400/

相关文章:

java - 通过列表属性内的参数查询实体

java - OutOfMemory - Sonar 无法分析项目源代码,也找不到问题

带有 JPanel 的 Java 布局管理器

java - 如何将方法放入AsyncTask

android - 如何等待 2 个并行改造调用都完成?

Maven 故障安全插件 - SurefireBooterForkException : There was an error in the forked process (TypeNotPresentExceptionProxy)

c# - ASP.NET 网络 API 2 : ExceptionLogger and Exception Handler

java - 使用 java 刷新 Excel 查询

android - 查看项目android中的总 View 量

iphone - 如何使用iPhone的崩溃报告查找问题?