fun main() {
try {
// Step 1: Attempting some code that may throw an exception
val result = divide(10, 0)
println("Result: $result")
} catch (e: ArithmeticException) {
// Step 2: Handling a specific type of exception (ArithmeticException)
println("Caught an arithmetic exception: ${e.message}")
} catch (e: Exception) {
// Step 3: Handling a more general type of exception (Exception)
println("Caught a general exception: ${e.message}")
} finally {
// Step 4: Code that will always be executed, whether an exception is thrown or not
println("Finally block executed")
}
}
fun divide(a: Int, b: Int): Int {
// Step 5: Throwing an exception if the divisor (b) is zero
if (b == 0) {
throw ArithmeticException("Cannot divide by zero")
}
// Step 6: Returning the result if no exception is thrown
return a / b
}