β οΈ Exception Handling
π What are Exceptions?β
Exceptions are errors that occur during program execution. When you handle exceptions well, your program runs stably without stopping!
π‘ Basic try-catchβ
Basic Usageβ
fun main() {
try {
val result = 10 / 0 // Error occurs!
println(result)
} catch (e: Exception) {
println("Error occurred: ${e.message}")
}
// Error occurred: / by zero
println("Program continues running!")
}
Handling Specific Exceptionsβ
fun main() {
try {
val text = "abc"
val number = text.toInt() // NumberFormatException
} catch (e: NumberFormatException) {
println("Cannot convert to number: ${e.message}")
} catch (e: Exception) {
println("Unknown error: ${e.message}")
}
}
finallyβ
fun main() {
try {
println("Starting task")
// Perform task
} catch (e: Exception) {
println("Error occurred")
} finally {
println("Cleanup (always executed)")
}
}
π― Practical Examplesβ
Safe Number Conversionβ
fun safeToInt(text: String): Int? {
return try {
text.toInt()
} catch (e: NumberFormatException) {
null
}
}
fun main() {
println(safeToInt("123")) // 123
println(safeToInt("abc")) // null
val age = safeToInt("25") ?: 0
println("Age: $age")
}
File Reading Simulationβ
class FileReader {
fun readFile(filename: String): String {
if (filename.isEmpty()) {
throw IllegalArgumentException("Filename is empty")
}
if (!filename.endsWith(".txt")) {
throw IllegalArgumentException("Only text files are supported")
}
return "File content: $filename"
}
}
fun main() {
val reader = FileReader()
try {
val content = reader.readFile("data.txt")
println(content)
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}
try {
reader.readFile("")
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
// Error: Filename is empty
}
}
User Input Validationβ
data class User(val name: String, val age: Int)
fun createUser(name: String, age: Int): User {
require(name.isNotBlank()) { "Name is required" }
require(age > 0) { "Age must be positive" }
require(age < 150) { "Age is too high" }
return User(name, age)
}
fun main() {
try {
val user1 = createUser("Hong Gildong", 25)
println(user1)
val user2 = createUser("", 25) // Error!
} catch (e: IllegalArgumentException) {
println("Validation failed: ${e.message}")
// Validation failed: Name is required
}
}
API Response Handlingβ
sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
}
fun divide(a: Int, b: Int): Result<Int> {
return try {
Result.Success(a / b)
} catch (e: ArithmeticException) {
Result.Error(e)
}
}
fun main() {
val result1 = divide(10, 2)
when (result1) {
is Result.Success -> println("Result: ${result1.data}")
is Result.Error -> println("Error: ${result1.exception.message}")
}
val result2 = divide(10, 0)
when (result2) {
is Result.Success -> println("Result: ${result2.data}")
is Result.Error -> println("Error: ${result2.exception.message}")
}
}
π Using as an Expressionβ
try as a Valueβ
fun main() {
val number = try {
"123".toInt()
} catch (e: NumberFormatException) {
0 // Default value
}
println(number) // 123
val invalid = try {
"abc".toInt()
} catch (e: NumberFormatException) {
-1
}
println(invalid) // -1
}
Chainingβ
fun safeDivide(a: Int, b: Int): Int? {
return try {
a / b
} catch (e: ArithmeticException) {
null
}
}
fun main() {
val result = safeDivide(10, 2)
?.let { it * 2 }
?.let { it + 5 }
?: 0
println(result) // 15 (10/2 * 2 + 5)
}
π‘οΈ Writing Safe Codeβ
require vs checkβ
fun processOrder(quantity: Int, price: Int) {
// Input validation
require(quantity > 0) { "Quantity must be positive" }
require(price > 0) { "Price must be positive" }
val total = quantity * price
// State validation
check(total < 1000000) { "Total amount is too large" }
println("Order completed: $total won")
}
fun main() {
try {
processOrder(10, 5000) // Success
processOrder(-1, 5000) // require fails
} catch (e: IllegalArgumentException) {
println("Input error: ${e.message}")
} catch (e: IllegalStateException) {
println("State error: ${e.message}")
}
}
checkNotNullβ
fun processName(name: String?) {
val validName = checkNotNull(name) { "Name is null" }
println("Processing: $validName")
}
fun main() {
try {
processName("Hong Gildong") // Success
processName(null) // Fails
} catch (e: IllegalStateException) {
println("Error: ${e.message}")
}
}
runCatchingβ
A convenient method available since Kotlin 1.3!
fun main() {
// Using runCatching
val result = runCatching {
"123".toInt()
}
result
.onSuccess { println("Success: $it") }
.onFailure { println("Failure: ${it.message}") }
// getOrNull
val number = runCatching { "abc".toInt() }.getOrNull()
println(number) // null
// getOrDefault
val safe = runCatching { "abc".toInt() }.getOrDefault(0)
println(safe) // 0
}
π― Practical Patternsβ
Retry Logicβ
fun <T> retry(times: Int, block: () -> T): T? {
repeat(times) { attempt ->
try {
return block()
} catch (e: Exception) {
println("Attempt ${attempt + 1} failed: ${e.message}")
if (attempt == times - 1) throw e
}
}
return null
}
fun main() {
var count = 0
try {
val result = retry(3) {
count++
if (count < 3) {
throw Exception("Not yet ready")
}
"Success!"
}
println(result)
} catch (e: Exception) {
println("Final failure")
}
}
Resource Cleanupβ
class Resource : AutoCloseable {
init {
println("Resource created")
}
fun use() {
println("Resource used")
}
override fun close() {
println("Resource cleaned up")
}
}
fun main() {
try {
Resource().use { resource ->
resource.use()
// Automatically calls close()
}
} catch (e: Exception) {
println("Error occurred")
}
}
π€ Frequently Asked Questionsβ
Q1. When should I use throw?β
A: When you need to explicitly throw an exception!
fun validateAge(age: Int) {
if (age < 0) {
throw IllegalArgumentException("Age cannot be negative")
}
if (age > 150) {
throw IllegalArgumentException("Age is too high")
}
}
Q2. Exception vs RuntimeException?β
A: Kotlin doesn't distinguish!
// Java distinguishes between checked/unchecked
// Kotlin treats all as unchecked (no throws declaration needed)
fun divide(a: Int, b: Int): Int {
return a / b // No throws declaration needed!
}
Q3. What about custom exceptions?β
A: Inherit from Exception!
class InvalidEmailException(message: String) : Exception(message)
fun validateEmail(email: String) {
if (!email.contains("@")) {
throw InvalidEmailException("Invalid email: $email")
}
}
fun main() {
try {
validateEmail("invalid")
} catch (e: InvalidEmailException) {
println(e.message)
}
}
π¬ Conclusionβ
Build stable programs with exception handling!
Key Takeaways:
β
Handle exceptions with try-catch
β
Validate with require/check
β
Simplify with runCatching
β
Return values as expressions
β
Cleanup with finally
Next Step: Try working with files in File I/O!