目錄
- 1. kotlin 捕獲例外
- 2. kotlin 先處理小例外,再處理大例外
- 3. kotlin 使用 throw 拋出例外
- 4. kotlin 自定義例外
- 附 Github 原始碼:
1. kotlin 捕獲例外
- 不論在 try 塊、catch 塊中執行怎樣的代碼(除非退出虛擬機 System.exit(1) ),finally 塊的代碼總會被執行
// 定義頂級常量
const val fileName = "src/com/william/testkt/exception_demo.txt"
/**
* 寫入檔案,使用 try-catch 捕獲例外
*/
fun writeFile(src: String): Int {
var fos: FileOutputStream? = null
try {
val file = File(fileName)
fos = FileOutputStream(file)
fos.write(src.toByteArray())
return 1 // 會被 finally 塊中的代碼覆寫
} catch (e: Exception) {
e.printStackTrace()
return 2 // 會被 finally 塊中的代碼覆寫
} finally {
fos?.close()
return 3
}
}
/**
* 讀取檔案
*/
fun readFile(): String {
var fis: FileInputStream? = null
try {
val file = File(fileName)
val size = file.length().toInt()
fis = FileInputStream(file)
val sb = StringBuilder()
val buffer = ByteArray(size)
fis.read(buffer)
sb.append(String(buffer))
return sb.toString()
} catch (e: Exception) {
e.printStackTrace() // 列印堆疊資訊
return "${e.message}"
} finally {
println("finally")
fis?.close()
}
}
fun main() {
val result = writeFile("this is a simple message")
println(result) // 3
val text = readFile()
println(text)
}
2. kotlin 先處理小例外,再處理大例外
fun compute(obj: String?) {
try {
Integer.parseInt(obj)
} catch (e: RuntimeException) {
println("RuntimeException: ${e.message}")
} catch (e: Exception) {
println("Exception: ${e.message}")
}
}
3. kotlin 使用 throw 拋出例外
fun throwExFun(param: String?) {
if (param == null) {
throw NullPointerException()
}
}
4. kotlin 自定義例外
class CustomException : Exception {
// 無參構造
constructor() {}
// 帶參構造
constructor(msg: String) : super(msg) {}
}
fun throwCustomExFun(param: String?) {
if (param == null) {
// 使用 throw 拋出自定義例外
throw CustomException("param is null")
}
}
附 Github 原始碼:
TestException.kt
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374834.html
標籤:其他
下一篇:Kotlin 物件、列舉、委托
