Kotlin 异常处理
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")
}
}