⚠️ 例外処理
📖 例外とは?
**例外(Exception)**は、プログラム実行中に発生するエラーです。例外を適切に処理すれば、プログラムが停止せず安定的に動作します!
💡 基本的なtry-catch
基本的な使い方
fun main() {
try {
val result = 10 / 0 // エラー発生!
println(result)
} catch (e: Exception) {
println("エラー発生: ${e.message}")
}
// エラー発生: / by zero
println("プログラム継続実行!")
}
特定の例外処理
fun main() {
try {
val text = "abc"
val number = text.toInt() // NumberFormatException
} catch (e: NumberFormatException) {
println("数値に変換できません: ${e.message}")
} catch (e: Exception) {
println("不明なエラー: ${e.message}")
}
}
finally
fun main() {
try {
println("作業開始")
// 作業実行
} catch (e: Exception) {
println("エラー発生")
} finally {
println("クリーンアップ作業 (常に実行)")
}
}
🎯 実践例
安全な数値変換
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")
}