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")
    }
}


附 Github 源码:

TestException.kt

  • 11
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值