目录

  • 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? = nulltry {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? = nulltry {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) // 3val 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

Kotlin 异常处理相关推荐

  1. 2.8 Kotlin异常处理

    目录 Kotlin异常介绍: Kotlin异常处理: Kotlin throw关键字: kotlin 异常处理机制类似 Java 异常处理机制.但有一点不同,Java 中的异常分为两类,受检查异常 和 ...

  2. Kotlin 异常处理(try...catch,finally)

    一.Try-Catch 捕获分支异常的匹配类型 表达式,可以用来赋值 package net.println.kotlin.chapters/*** @author:wangdong* @descri ...

  3. kotlin异常处理之----取消异常CancellationException与其他异常的区别,协程异常处理顺序

    CancellationException异常是协程专门用来取消协程而使用,与其他异常在处理上是有区别的 协程内部使用CancellationException来进行取消操作,这个异常会被忽略掉. 当 ...

  4. BeginnersBook Kotlin 教程

    来源:ApacheCN BeginnersBook 翻译项目 译者:飞龙 协议:CC BY-NC-SA 4.0 贡献指南 本项目需要校对,欢迎大家提交 Pull Request. 请您勇敢地去翻译和改 ...

  5. 买《Kotlin从小白到大牛》专题视频课程,送配套纸质图书

    经过一年多时间的呕心沥血,Kotlin立体化图书--<Kotlin从小白到大牛>即将与大家见面了.所谓立体化图书包括:电子图书.视频.课件和服务等内容. <Kotlin从小白到大牛& ...

  6. Kotlin Monad的学习

    文章目录 0. 前言 1. 一些数学概念(该小节可以跳过) 1.1 半群 与 幺半群 1.2 范畴.态射 与 同态 1.3 函子 与 自函子 1.4 Monad 2. Monad 的一个模型 3. K ...

  7. shields 徽标_神经网络生成超级英雄徽标

    shields 徽标 Machine Learning is a superpower in the computer science world. We can use it to predict ...

  8. kotlin中的异常处理_如何使用assertFailsWith在Kotlin中测试异常

    kotlin中的异常处理 by Daniel Newton 丹尼尔·牛顿 如何使用assertFailsWith在Kotlin中测试异常 (How to test exceptions in Kotl ...

  9. Kotlin学习笔记29(完结篇) Flow part2 Flow的Buffer 中间操作符zip 打平 异常处理 Flow的完成 onCompletion的优势 onCompletion陷阱

    参考链接 示例来自bilibili Kotlin语言深入解析 张龙老师的视频 1  Buffer 缓冲 /*** Buffer 缓冲* 这里没有使用缓冲*/private fun myMethod() ...

最新文章

  1. 使用awk,sort和uniq从ATS访问日志中统计出异常链接域名的次数排名
  2. 斯坦佛编程教程-Unix编程工具(二)
  3. .Net与Oracle地数据库连接池(Connection Pool)
  4. 2021百度职业教育行业洞察
  5. 使用vscode连接阿里云服务器报错: ssh: Could not resolve hostname Name or service not known
  6. 阿里云下mysql远程访问被拒绝_记一次MySQL数据库拒绝访问的解决过程
  7. 大学计算机课作业新建文档,重庆大学2020年春季学期课程作业计算机组成原理.docx...
  8. Mac Big Sur右上角时间变灰的解决方法
  9. 手把手教你用python实现决策树的策略规则挖掘
  10. linux 环境变量详解,Linux 环境变量详解及实例
  11. 如何用js判断浏览器中是否安装有flash插件
  12. oracle 学习笔记 flashback query
  13. 单片机中断交通灯c语言程序设计,基于c语言单片机交通灯
  14. html怎么将背景图片旋转,css怎么旋转图片?
  15. 开放网络操作系统介绍(2)、SONiC
  16. jmeter-BeanShell预处理器与BeanShell后置处理器的使用
  17. POJ_2228 Naptime ( 环状dp )
  18. 控温/恒温烙铁操作方法及使用说明
  19. Linux自动化运维工具ansible详解
  20. mysql笛卡尔积的解释

热门文章

  1. 前端工程师如何突破瓶颈期
  2. ACL原理与类型、基本ACL与高级ACL
  3. 6-7 求一组数中的最大值、最小值和平均值 (10 分)
  4. 自适应滤波器:维纳滤波器2——LCMV及MVDR实现
  5. 一起做RGB-D SLAM调试
  6. mysql between详解_MySQL中BETWEEN子句的用法实例详解
  7. Nature子刊批判人工神经网络:先天结构比后天训练更重要,应该借鉴动物大脑...
  8. iOS-获取UIWebView或者WKWebView页面的视频连接
  9. olist巴西电商数据分析项目 sql+tableau
  10. Add correct host key in C:\\Users\\xxx/.ssh/known_hosts to get rid of this message.