Introduction
Error handling helps your program deal with problems without crashing. It keeps your app working smoothly and lets you fix issues nicely.
Error handling helps your program deal with problems without crashing. It keeps your app working smoothly and lets you fix issues nicely.
try { // code that might cause an error } catch (e: Exception) { // code to handle the error } finally { // code that runs no matter what }
try block holds code that might cause an error.
catch block handles the error if it happens.
try { val number = "abc".toInt() } catch (e: NumberFormatException) { println("That is not a number!") }
try { val result = 10 / 0 } catch (e: ArithmeticException) { println("Cannot divide by zero!") }
This program tries to change text to a number. If it fails, it tells the user. It always prints a final message.
fun main() { val input = "hello" try { val number = input.toInt() println("Number is $number") } catch (e: NumberFormatException) { println("Oops! '$input' is not a number.") } finally { println("End of program.") } }
Always handle errors to avoid program crashes.
Use finally to run code no matter what, like closing files.
Error handling keeps programs safe and user-friendly.
Use try and catch to manage problems.
Good error handling helps fix issues and keeps apps running.
try to start a block and catch (e: Exception) to handle errors.try { ... } catch (e: Exception) { ... }.fun main() {
try {
val result = 10 / 0
println(result)
} catch (e: ArithmeticException) {
println("Error caught: Division by zero")
}
}fun main() {
try {
val text = "abc"
val number = text.toInt()
} catch e: NumberFormatException {
println("Invalid number")
}
}catch (e: Exception).catch e: NumberFormatException without parentheses, causing syntax error.fun readInt(): Int {
// Your code here
}Pass the test and this pattern moves unknown