Issue
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.
Thanks.
Solution
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.
Answered By - mattlaabs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.