kotlin中的异常处理_Kotlin异常处理

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 Java Java中的已检查与未检查异常
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) {
    try {

        var a = 0
        var x = 7 / a

        val 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) {
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.fail

class User {
    var name: String? = ""

}

fun main(args: Array) {

    var user = User()
    user.name = null

    val 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.

kotlin中的异常处理_Kotlin异常处理_第1张图片

如果执行了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) {

    var user = User()
    user.name = null

    val 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) {

    simpleTryCatch {
        var x = 0
        var y = 7
        var 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中的异常处理

你可能感兴趣的:(堆栈,python,java,exception,go)