kotlin中的异常处理

In this tutorial, we’ll be discussing Exception Handling in Kotlin.

在本教程中,我们将讨论Kotlin中的异常处理。

什么是例外? (What are Exceptions?)

Exceptions are something that can break your program. That makes Exception Handling an essential part of any Programming Language. Using Exception handling you can handle errors and prevent runtime crashes that can stop your program. Instead, using Exception Handling you can handle failed conditions gracefully and continue with your program flow.

异常可能会破坏您的程序。 这使得异常处理成为所有编程语言的重要组成部分。 使用异常处理,您可以处理错误并防止可能导致程序停止的运行时崩溃。 相反,使用异常处理可以优雅地处理失败的条件并继续执行程序流程。

Checked vs Unchecked Exceptions in JavaJava中的已检查与未检查异常
Checked Exceptions are typically set on methods and are checked at compile time.
Checked Exception通常在方法上设置,并在编译时进行检查。
On the contrary, Unchecked exceptions derive from RuntimeExceptions and are checked at runtime.
相反,未检查的异常是从RuntimeExceptions派生的,并在运行时进行检查。

Kotlin例外 (Kotlin Exceptions)

All Exceptions descend from the Throwable class.
To throw an exception we use the throw keyword.

所有异常均来自Throwable类。
要抛出异常,我们使用throw关键字。

throw Exception("Oops. Something went wrong")

In Kotlin there are no checked exceptions. That means there is no throws keyword.

在Kotlin中,没有检查过的异常。 这意味着没有throws关键字。

最终尝试捕获 (try-catch-finally)

To handle exceptions we use the try-catch block. The piece of code that has a possibility to give an exception is set inside the try block. The exception is caught inside the catch block. Irrespective of what happens, the finally block is always run.
The finally blocks is optional. It’s generally used to release any resources that were used in the try-catch.
Typically a try can have multiple catches. Only the first matching catch would be run. Hence it’s recommended to stack the catches in the order: Specific Exception to General Exception.

为了处理异常,我们使用try-catch块。 在try块中设置了可能给出异常的代码段。 异常捕获在catch块内。 无论发生什么情况,finally块始终运行。
finally块是可选的。 通常用于释放try-catch中使用的任何资源。
通常,一次尝试可以有多个收获。 只运行第一个匹配的捕获。 因此,建议按以下顺序堆叠捕获:特定异常到通用异常。

fun main(args: Array<String>) {try {var a = 0var x = 7 / aval v = "Journaldev.com"v.toInt()} catch (e: ArithmeticException) {println("Arthimetic Exception")} catch (e: Exception) {println("Exception occured. To print stacktrace use e")} finally {println("Finally. It's over")}
}//Prints
//Arthimetic Exceptions

Once an exception in the try block is found, it’ll not execute anything else in that try block.
We can even use a try with a finally.

一旦在try块中发现异常,它将不会在该try块中执行其他任何操作。
我们甚至可以try使用finally

try{throw Exception("Hi. how are you?")}finally {println("Finally. Good.")}

With a try, at least one catch or finally block must be present.
throw is an expression which would print the stack trace as well.

尝试一下,必须至少存在一个陷阱或最后一个障碍。
throw是一个将打印堆栈跟踪信息的表达式。

尝试是一种表达 (Try is an expression)

The value executed in a try-catch block can be returned and stored in a variable.

可以在try-catch块中执行的值可以返回并存储在变量中。

fun main(args: Array<String>) {
var x= "Androidly.net"
var a = try { x.toInt() } catch (e: NumberFormatException) { "This is a string" }
println(a)
x = "5"
a = try { x.toInt() } catch (e: NumberFormatException) { "This is a string" }
println(a)
}

In the above code, we’re able to set the variable a with two different type of values.
If the try statement doesn’t execute the value of catch is set.
Irrespective of which is set, the finally statement is never set as the expression.

在上面的代码中,我们能够为变量a设置两种不同类型的值。
如果try语句不执行,则设置catch的值。
无论设置了哪个, finally语句都不会设置为表达式。

失败功能 (fail function)

This is a shorthand for catching exceptions as shown below.

这是捕获异常的快捷方式,如下所示。

import kotlin.test.failclass User {var name: String? = ""}fun main(args: Array<String>) {var user = User()user.name = nullval n: String = user.name ?: fail("No name found")print(5)
}

If the fail statement is executed the program won’t run after it’s printed.

如果执行了fail语句,则程序在打印后将无法运行。

Implicitly the fail statement contains a throw keyword.
The fail function looks like this:

隐式地,fail语句包含throw关键字。
fail函数如下所示:

fun fail(message: String): Nothing {throw IllegalArgumentException(message)
}

Nothing is a special return type which throw returns.

没有什么是抛出收益的特殊收益类型。

In the above example, the fail function prints the stack trace too which we don’t always want.
We can override the fail function to just print the message.

在上面的示例中,fail函数也会打印我们并不总是想要的堆栈跟踪。
我们可以覆盖fail函数以仅打印消息。

class User {var name: String? = ""
}
fun main(args: Array<String>) {var user = User()user.name = nullval n: String = user.name ?: fail("No name found")println(n)print(10)}
fun fail(message: String): Nothing {val throwable = Throwable(message)Thread.setDefaultUncaughtExceptionHandler { t, e -> System.err.println(e.message) }throw throwable
}//Prints
No name found

将内联函数与异常处理一起使用 (Using Inline Functions with exception handling)

We’ve discussed Inline Functions in Kotlin here.
Why use Inline Functions?
They cause no overhead.

我们已经在讨论Kotlin内联函数在这里 。
为什么要使用内联函数?
它们不会造成开销。

Now, we’ve seen that try-catch blocks can get messy and verbose.
Let’s use an inline function to make it concise since that’s where the strength of Kotlin code lies in.

现在,我们已经看到try-catch块会变得凌乱和冗长。
让我们使用内联函数使其简洁,因为这正是Kotlin代码的优势所在。

fun main(args: Array<String>) {simpleTryCatch {var x = 0var y = 7var z = y / x}simpleTryCatch {var x = "Androidly"var number = x.toInt()}
}inline fun simpleTryCatch(action: () -> Unit) {try {action()} catch (t: Throwable) {println("Caught something. ${t.message}")}
}

This brings an end to this Kotlin tutorial on Exception handling.

这结束了有关异常处理的Kotlin教程。

翻译自: https://www.journaldev.com/20444/kotlin-exception-handling

kotlin中的异常处理

kotlin中的异常处理_Kotlin异常处理相关推荐

  1. kotlin中判断字符串_Kotlin程序查找字符串中字符的频率

    kotlin中判断字符串 Given a string and a character, we have to find the frequency of the character in the s ...

  2. kotlin中判断字符串_Kotlin程序删除字符串中所有出现的字符

    kotlin中判断字符串 Given a string and a character, we have to remove all occurrences of the character in g ...

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

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

  4. SpringMVC中利用HandlerExceptionResolver完成异常处理

    SpringMVC中利用HandlerExceptionResolver完成异常处理 参考文章: (1)SpringMVC中利用HandlerExceptionResolver完成异常处理 (2)ht ...

  5. PHP中try{}catch{}是异常处理.

    PHP中try{}catch{}是异常处理. 参考文章: (1)PHP中try{}catch{}是异常处理. (2)https://www.cnblogs.com/wangfeng3306/p/104 ...

  6. java jsp公共异常页面_实际应用中JSP页面的异常处理

    打开浏览器,访问一个链接或者输入url,"咚"的敲下回车... 哗啦啦,一大堆看不懂的异常信息一下×××出来,塞满整个页面,我勒个去,吓死人了... 在实际开发中,用户访问网站的时 ...

  7. python里try和except用法_Python中的错误和异常处理简单操作示例【try-except用法】...

    本文实例讲述了Python中的错误和异常处理操作.分享给大家供大家参考,具体如下: #coding=utf8 print ''''' 程序编译时会检测语法错误. 当检测到一个错误,解释器会引发一个异常 ...

  8. python的try和except用法_Python中的错误和异常处理简单操作示例【try-except用法】...

    本文实例讲述了Python中的错误和异常处理操作.分享给大家供大家参考,具体如下: #coding=utf8 print ''''' 程序编译时会检测语法错误. 当检测到一个错误,解释器会引发一个异常 ...

  9. kotlin中既继承又实现_Kotlin程序| 解决继承中的主要冲突的示例

    kotlin中既继承又实现 继承中的主要冲突 (Overriding Conflicts in Inheritance) It may appear, we inherit more than one ...

最新文章

  1. C++核心编程(一)
  2. R语言使用download.file函数下载网络文件到本地(Download File from the Internet)
  3. 提高工作效率-shell操作快捷键
  4. php程序监听node.js程序和go程序
  5. 网络优化实践探索文章
  6. 文献记录(part37)--A two-stage hybrid ant colony optimization for high-dimensional feature selection
  7. 微软发布Azure Stack更多细节,预计9月交付
  8. python百度翻译接口_python3 调用百度翻译API翻译英文
  9. c#winform演练 ktv项目 点击歌单行 可以播放对应的歌曲
  10. GROUP BY你都不会!ROLLUP,CUBE,GROUPPING详解
  11. ubuntu16.04 安装cuda9.0+cudnn7.0.5+tensorflow+nvidia-docker配置GPU服务
  12. Bootstrap补充
  13. linux系统下聊天工具,linux系统环境下如何使用amsn聊天工具_linux教程
  14. 从Demo到Engine(二) -- Render Queue Sort
  15. 猫叫了,老鼠跑了!(复习委托和事件)
  16. iis 服务器修复,如何修复未找到的Windows 10 inetmgr(IIS管理器)
  17. 干货!自监督学习在推荐系统中的应用
  18. python爬虫之数据提取、正则表达式、xml、XPath、etree、CSS选择器 BeautifulSoup4
  19. Tackling Climate Change with Machine Learning
  20. Linux 文字雨特效

热门文章

  1. 80后营销人如何为理想插上丰满“羽翼”?
  2. [转载] python(numpy) 实现神经网络训练 (卷积 全连接 池化)
  3. 利用apache 的PropertyUtilsBean 实现map和pojo相互转换
  4. JS === 实现通过点击td 跳转相应的图片
  5. zabbix--基础概念及原理
  6. Echo团队Alpha冲刺随笔 - 第六天
  7. .net core部署到Ubuntu碰到的问题
  8. V-rep学习笔记:机器人逆运动学数值解法(Damped Least Squares / Levenberg-Marquardt Method)...
  9. python自学记录 pydev安装
  10. opensuse 11.2/11.3安装vmware server 1.0.10笔记