0

What is try-catch in Kotlin?

What does try{...} catch{...} do in Kotlin? I saw someone using these in dividing something by zero but didn't understand what these code block do.. Can someone tell me what does these try-catch block do?

30th Oct 2019, 1:49 PM
Plaban Kr. Mondal
Plaban Kr. Mondal - avatar
3 Antworten
+ 3
I don't know Kotlin but I think it's built from Java. The try block tests the code in the block for an error while being executed and the catch allows you to define a block of code to be executed if an error occurs in the try block. So in the code here I take in a string and try to convert it into a double, but if the string is "ffxjgtc" and not a number there would be an error when you try to convert it. So then catch "catches" the error and then executes the code in the catch block. https://code.sololearn.com/cw9CMPw0gmjP/?ref=app
30th Oct 2019, 2:59 PM
Odyel
Odyel - avatar
+ 5
Odyel is right as it functions the same as the Java one. Normally, I use them to catch user input errors, but they can be used for many reasons. For example, you are nested twenty levels of recursive calls and need to pop back to the top. Before exceptions, you needed to pass a flag back telling each level above to abort. With an exception, the abort of all levels is done with a single throw. They don't even need to know. However, if they happen to have cleanup that is required, they can do a try and a finally without the catch. The finally code is run whether the try code completes or not perfect to handle cleaning up.
30th Oct 2019, 11:02 PM
John Wells
John Wells - avatar
0
Thanks
30th Oct 2019, 5:34 PM
Plaban Kr. Mondal
Plaban Kr. Mondal - avatar