脚本宝典收集整理的这篇文章主要介绍了Kotlin 异常处理,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
// 定义顶级常量
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)
}
fun compute(obj: String?) {
try {
Integer.parseInt(obj)
} catch (e: RuntimeException) {
println("RuntimeException: ${e.message}")
} catch (e: Exception) {
println("Exception: ${e.message}")
}
}
fun throwExFun(param: String?) {
if (param == null) {
throw NullPointerException()
}
}
class CustomException : Exception {
// 无参构造
constructor() {}
// 带参构造
constructor(msg: String) : super(msg) {}
}
fun throwCustomExFun(param: String?) {
if (param == null) {
// 使用 throw 抛出自定义异常
throw CustomException("param is null")
}
}
TestException.kt
以上是脚本宝典为你收集整理的Kotlin 异常处理全部内容,希望文章能够帮你解决Kotlin 异常处理所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。