是否有“双重”尝试捕获块?
是否有一种方法可以在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了避免通过在 catch -block中重复 try block(如 @luk2302提到)中重复代码,您应该考虑在功能中添加重试参数并致电它递归,就像:
对于多次重试,您可以使用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:
For multiple retries, you can use an Int instead and decrement until you hit 0.
您只想添加一种“尝试阈值”
如果 LUK2302。但是,老实说,在代码清洁度方面,它看起来有些怀疑:
If you want just to add kind of "attempts threshold" you could use something like that:
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:捕捉
例外
通常是不好的做法。如果您不编写某种框架代码以不同的形式重新抛弃异常,则应该知道可以抛出哪种业务例外并只捕获这些异常。让其余的代码完成工作以处理其他类型的异常。您尚未从捕获块中共享代码,但是鉴于您捕获了常规
exception
,似乎您没有提取有关确切例外的信息,也没有重新启动。在这种情况下,在我看来,您应该只是将内容提取到如果算法错误的情况下返回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:You might not need to do that for the second function, but I figured it would be more symmetrical.