Home > OS >  Is there a "double" try and catch block?
Is there a "double" try and catch block?

Time:06-26

Is there a way to use a try and 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
}

Thanks.

CodePudding user response:

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
        }
    }
}
    

CodePudding user response:

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.

  • Related