Complete the code to catch an exception and print a message.
try { val result = 10 / [1] println("Result: $result") } catch (e: Exception) { println("Error occurred") }
Dividing by zero causes an exception, so catching it shows why error handling matters.
Complete the code to throw an exception when input is negative.
fun checkNumber(num: Int) {
if (num < [1]) {
throw IllegalArgumentException("Negative number not allowed")
}
}We check if the number is less than zero to detect negative numbers.
Fix the error in the catch block to print the exception message.
try { val data = "abc".toInt() } catch (e: Exception) { println(e[1]) }
In Kotlin, exception messages are accessed with the property message without parentheses.
Fill both blanks to handle a NumberFormatException and print a custom message.
try { val num = "abc".toInt() } catch (e: [1]) { println("[2]") }
We catch NumberFormatException and print a message explaining the error.
Fill all three blanks to create a function that safely parses an integer or returns null.
fun safeParseInt(str: String): Int? {
return try {
str[1]toInt()
} catch (e: [2]) {
[3]
}
}The dot operator calls toInt(). We catch NumberFormatException and return null if parsing fails.