是否有“双重”尝试捕获块?

发布于 2025-02-10 10:22:16 字数 402 浏览 1 评论 0原文

是否有一种方法可以在Kotlin中使用try-catch进行

try {
 // First try, if it throws an exception, try next try block
} try {
 // Second try, if it throws an exception, too, go to exception block
} catch (e: Exception) {
 // Handle exception
}

编辑

,因此,假设有两种加密算法和一个加密字符串,但是您不知道哪个已用于加密该字符串。这些算法非常具体,没有try-catch该应用将崩溃。这就是为什么我需要通过两个尝试块。

Is there a way to use a try-catch in Kotlin like this

try {
 // First try, if it throws an exception, try next try block
} try {
 // Second try, if it throws an exception, too, go to exception block
} catch (e: Exception) {
 // Handle exception
}

Edit

So, let's say there are two encryption algorithms and one encrypted string, but you do not know which one has been used to encrypt that string. Those algorithms are very specific and without try-catch the app would crash. That's why I need to go through two try blocks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花辞树 2025-02-17 10:22:16

为了避免通过在 catch -block中重复 try block(如 @luk2302提到)中重复代码,您应该考虑在功能中添加重试参数并致电它递归,就像:

fun doStuff(retry: Boolean = true) {
  try {
    ...
  } catch (e: Exception) {
    if (retry)
      return doStuff(retry = false)
    ... // handle exception
  }

对于多次重试,您可以使用int并减少直到达到0。

To avoid code duplicating by repeating your try-block in your catch-block (as mentioned by @luk2302), you should consider adding a retry-parameter to your function and call it recursively, like:

fun doStuff(retry: Boolean = true) {
  try {
    ...
  } catch (e: Exception) {
    if (retry)
      return doStuff(retry = false)
    ... // handle exception
  }

For multiple retries, you can use an Int instead and decrement until you hit 0.

无所谓啦 2025-02-17 10:22:16

您只想添加一种“尝试阈值”

private var attempts = 0

fun doSomething() {
    try {
        // your code with potential exception
    } catch (e: Exception) {
        if (++attempts > 1) // handle exception
        else doSomething()
    }
}

如果 LUK2302。但是,老实说,在代码清洁度方面,它看起来有些怀疑:

fun doSomething() {
    try {
        // your code with potential exception
    } catch (e: Exception) {
        try {
            // your code with potential exception
        } catch (e: Exception) {
            // handle exception
        }
    }
}
    

If you want just to add kind of "attempts threshold" you could use something like that:

private var attempts = 0

fun doSomething() {
    try {
        // your code with potential exception
    } catch (e: Exception) {
        if (++attempts > 1) // handle exception
        else doSomething()
    }
}

If you really need a nested try-catch then you can follow the approach by @luk2302. But, to be honest, it looks a little bit doubtful in terms of code cleanliness:

fun doSomething() {
    try {
        // your code with potential exception
    } catch (e: Exception) {
        try {
            // your code with potential exception
        } catch (e: Exception) {
            // handle exception
        }
    }
}
    
傻比既视感 2025-02-17 10:22:16

捕捉例外通常是不好的做法。如果您不编写某种框架代码以不同的形式重新抛弃异常,则应该知道可以抛出哪种业务例外并只捕获这些异常。让其余的代码完成工作以处理其他类型的异常。

您尚未从捕获块中共享代码,但是鉴于您捕获了常规exception,似乎您没有提取有关确切例外的信息,也没有重新启动。在这种情况下,在我看来,您应该只是将内容提取到如果算法错误的情况下返回null的函数,甚至首先没有这个问题:

fun decrypt(msg: String): String {
    return decryptWithAlgo1OrNull(msg) ?: decryptWithAlgo2OrNull(msg) ?: handleFailureOfBoth()
}

private fun decryptWithAlgo1OrNull(msg: String): String? = try {
    // algo 1 decyrption
} catch (e: SpecificAlgo1Exception) {
    null
}
private fun decryptWithAlgo2OrNull(msg: String): String? = try {
    // algo 2 decyrption
} catch (e: SpecificAlgo2Exception) {
    null
}

您可能不需要为第二个功能而做我认为这会更对称。

Catching Exception is bad practice in general. If you're not writing some kind of framework code that rethrows the exceptions in a different form, you should know what business exception can be thrown and only catch those. Let the rest of the code do the work to handle other types of exceptions.

You haven't shared the code from the catch block, but given that you catch the general Exception, it seems that you don't extract information about the exact exception nor re-throw. In that case, it seems to me that you should just be extracting stuff into functions that return null in case of wrong algorithm, and not even have this problem in the first place:

fun decrypt(msg: String): String {
    return decryptWithAlgo1OrNull(msg) ?: decryptWithAlgo2OrNull(msg) ?: handleFailureOfBoth()
}

private fun decryptWithAlgo1OrNull(msg: String): String? = try {
    // algo 1 decyrption
} catch (e: SpecificAlgo1Exception) {
    null
}
private fun decryptWithAlgo2OrNull(msg: String): String? = try {
    // algo 2 decyrption
} catch (e: SpecificAlgo2Exception) {
    null
}

You might not need to do that for the second function, but I figured it would be more symmetrical.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文