Reputation: 1765
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
}
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.
Upvotes: 1
Views: 2650
Reputation: 37720
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.
Upvotes: 0
Reputation: 486
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.
Upvotes: 1
Reputation: 532
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
}
}
}
Upvotes: 1