Introduction
Exception handling is a mechanism to handle runtime errors, ensuring that the normal flow of the program is not disrupted. Kotlin provides a robust mechanism for handling exceptions using try
, catch
, finally
, and throw
keywords. This chapter will cover the syntax and usage of these keywords with examples.
Basics of Exception Handling
Syntax
try {
// Code that may throw an exception
} catch (e: ExceptionType) {
// Code to handle the exception
} finally {
// Code that will always execute
}
Example
fun main() {
try {
val result = 10 / 0
println("Result: $result")
} catch (e: ArithmeticException) {
println("Exception caught: ${e.message}")
} finally {
println("Finally block executed")
}
}
Explanation:
try { ... }
: Contains code that may throw an exception.catch (e: ArithmeticException) { ... }
: Catches the exception and handles it.finally { ... }
: Contains code that will always execute, regardless of whether an exception is thrown or not.
Output:
Exception caught: / by zero
Finally block executed
Throwing Exceptions
You can throw an exception explicitly using the throw
keyword.
Example
fun main() {
try {
checkAge(15)
} catch (e: Exception) {
println("Exception caught: ${e.message}")
}
}
fun checkAge(age: Int) {
if (age < 18) {
throw IllegalArgumentException("Age must be at least 18")
}
}
Explanation:
throw IllegalArgumentException("Age must be at least 18")
: Throws anIllegalArgumentException
if the age is less than 18.
Output:
Exception caught: Age must be at least 18
Multiple Catch Blocks
You can use multiple catch blocks to handle different types of exceptions.
Example
fun main() {
try {
val numbers = listOf(1, 2, 3)
println(numbers[5])
} catch (e: IndexOutOfBoundsException) {
println("Exception caught: ${e.message}")
} catch (e: Exception) {
println("General exception caught: ${e.message}")
} finally {
println("Finally block executed")
}
}
Explanation:
catch (e: IndexOutOfBoundsException) { ... }
: CatchesIndexOutOfBoundsException
.catch (e: Exception) { ... }
: Catches any other exceptions that are not caught by the previous catch block.
Output:
Exception caught: Index 5 out of bounds for length 3
Finally block executed
Custom Exceptions
You can create custom exceptions by extending the Exception
class.
Example
fun main() {
try {
validateName("")
} catch (e: InvalidNameException) {
println("Exception caught: ${e.message}")
}
}
class InvalidNameException(message: String) : Exception(message)
fun validateName(name: String) {
if (name.isEmpty()) {
throw InvalidNameException("Name cannot be empty")
}
}
Explanation:
class InvalidNameException(message: String) : Exception(message)
: Defines a custom exception classInvalidNameException
.throw InvalidNameException("Name cannot be empty")
: Throws the custom exception if the name is empty.
Output:
Exception caught: Name cannot be empty
Try as an Expression
In Kotlin, try
can be used as an expression, returning a value.
Example
fun main() {
val result = try {
val number = "10a".toInt()
number
} catch (e: NumberFormatException) {
-1
}
println("Result: $result")
}
Explanation:
val result = try { ... } catch (e: NumberFormatException) { ... }
: Usestry
as an expression to return a value based on whether an exception is thrown.
Output:
Result: -1
Example Program with Exception Handling
Here is an example program that demonstrates various aspects of exception handling in Kotlin:
fun main() {
// Using try-catch-finally
try {
val result = divide(10, 0)
println("Result: $result")
} catch (e: ArithmeticException) {
println("Exception caught: ${e.message}")
} finally {
println("Finally block executed")
}
// Using custom exception
try {
validateAge(15)
} catch (e: InvalidAgeException) {
println("Exception caught: ${e.message}")
}
// Using try as an expression
val number = try {
"123a".toInt()
} catch (e: NumberFormatException) {
-1
}
println("Parsed number: $number")
}
fun divide(a: Int, b: Int): Int {
return a / b
}
fun validateAge(age: Int) {
if (age < 18) {
throw InvalidAgeException("Age must be at least 18")
}
}
class InvalidAgeException(message: String) : Exception(message)
Output:
Exception caught: / by zero
Finally block executed
Exception caught: Age must be at least 18
Parsed number: -1
Conclusion
In this chapter, you learned about exception handling in Kotlin, including how to use try
, catch
, finally
, and throw
keywords. You also learned how to create custom exceptions and use try
as an expression. Exception handling is crucial for writing robust and maintainable Kotlin programs, as it allows you to handle runtime errors gracefully and ensure the normal flow of your application.