Implement Retry Logic in Kotlin
This article explores different ways to implement the retry logic in Kotlin.
The idea is to write our code within a try-catch block inside a loop that executes the specified number of times (the maximum retry value). For example, consider the below code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import kotlin.random.Random const val MAX_RETRIES = 10 fun main() { for (i in 0..MAX_RETRIES) { try { // generate 0 or 1 with equal probability val zeroOrOne = Random.nextInt(2) println("Random number is.. $zeroOrOne") // 50% probability of "ArithmeticException: / by zero" val rand = 1 / zeroOrOne // don't retry on success break } catch (e: ArithmeticException) { // handle exception println(e.message) // log the exception // optionally sleep for 1 seconds before retrying Thread.sleep(1000) // throw exception if the last re-try fails if (i == MAX_RETRIES) { throw e } } } } |
Output (will vary):
Random number is.. 0
/ by zero
Random number is.. 0
/ by zero
Random number is.. 0
/ by zero
Random number is.. 1
If the code throws an ArithmeticException, the control goes to the catch block. After handling the exception, retry happens after 1 second. The system throws the exception only when all retries are exhausted and the last retry fails.
That’s all about implementing retry logic in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)