栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Kotlin 异常处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Kotlin 异常处理

目录
    • 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"


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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645005.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号