swift 抛出错误_Swift错误处理– Swift尝试,捕捉,抛出

swift 抛出错误

Swift error handling is a very important aspect of writing better code. Swift try statement is used for error handling in swift programs. Let’s get started by launching XCode playground.

Swift错误处理是编写更好的代码的一个非常重要的方面。 Swift try语句用于swift程序中的错误处理。 让我们开始启动XCode游乐场。

快速错误处理 (Swift Error Handling)

Swift Error Handling is all about handling the failing conditions gracefully.

Swift错误处理就是关于优雅地处理失败情况的一切。

An error can lead to runtime errors or changes in the flow of the program.

错误可能导致运行时错误或程序流程更改。

We come across different kinds of errors in our projects:

我们在项目中遇到了各种错误:

  • Logic Errors

    逻辑错误
  • Type Conversion Errors.

    类型转换错误。
  • External Errors such as FileNotFound etc.

    外部错误,例如FileNotFound等。

The brute force way to handle errors is by using if else statements where we check each and every possible error. But this can lead to bloated codes with too many nested conditions.

处理错误的暴力方式是使用if else语句 ,在该语句中我们检查每个可能的错误。 但是,这可能导致嵌套条件过多的代码膨胀。

In Swift, Errors are just values of a certain type. Swift does not support checked exceptions.

在Swift中,错误只是某种类型的值。 Swift不支持检查的异常。

快速错误协议 (Swift Error Protocol)

Error Protocol is just a type for representing error values that can be thrown.
错误协议只是一种表示可以抛出的错误值的类型。

Swift requires you to create a custom Error type. Typically an Enum is used which conforms to the Error Protocol.

Swift要求您创建自定义错误类型。 通常,使用符合错误 协议Enum

The Error Protocol is more or less empty. Hence you don’t need to override anything from them. Error Protocol is a must for Error Handling and creating Error types.

错误协议或多或少是空的。 因此,您不需要覆盖它们中的任何内容。 错误协议是错误处理和创建错误类型的必要条件。

Let’s create a basic enum which conforms to this Error Protocol.

让我们创建一个符合此错误协议的基本枚举。

enum UserDetailError: Error {
    case noValidName
    case noValidAge
}

Now let’s use this Error Type in our classes and functions.

现在,让我们在类和函数中使用此错误类型。

抛出 (throws and throw)

If a function or an initializer can throw an error, the throws modifier must be added in the definition itself right after the paratheses and just before the return type.

如果函数或初始化程序可能引发错误,则必须在定义本身中的parases之后和返回类型之前,将throws修饰符添加到定义本身中。

func userTest() throws -> <Return Type> {

}

The throws keyword would propagate the error from the function to the calling code.
Otherwise, a non-throwing function must handle the error inside that function’s code itself.

throws关键字会将错误从函数传播到调用代码。
否则,非抛出函数必须处理该函数代码本身内部的错误。

throw keyword is used for throwing errors from the error type defined.

throw关键字用于从定义的错误类型throw错误。

Let’s look at an example demonstrating throws and throw in a function:

让我们看一个演示throw和throw in函数的示例:

func userTest() throws {
    if <condition_matches> {
    //Add your function code here
    }
    else{
    throw UserDetailError.noValidName
    }
}

In Error Handling, guard let is useful in the sense that we can replace the return statement in the else block with the throwing error. This prevents too many if else conditions.
Let’s look at it with the example below.

在错误处理中,在让我们可以将thing错误替换为else块中的return语句的意义上,保护让出很有用。 这样可以防止太多其他情况。
让我们用下面的例子来看它。

func userTest(age: Int, name: String) throws {
    
    guard age > 0 else{
    throw UserDetailError.noValidAge
    }
    
    guard name.count > 0 else{
       throw UserDetailError.noValidName
    }
}

Note: You cannot add the Error type after the throws keyword in Swift.

注意:您不能在Swift中的throws关键字之后添加Error类型。

In the above code, if the condition in the guard let fails it’ll throw an error and the function would return there itself.
Let’s look at how to handle these errors.

在上面的代码中,如果guard let中的条件失败,则会引发错误,并且函数将自行返回。
让我们看看如何处理这些错误。

快速尝试,赶上 (Swift try, do-catch)

In Swift, contrary to Java, do-catch block is used to handle errors in place of try-catch.

与Java相反,在Swift中, do-catch块用于代替try-catch处理错误。

Every function that has throws needs to set in the try statement since it has a potential error.

每个抛出的函数都需要在try语句中进行设置,因为它有潜在的错误。

Swift try statement is executed only when it is inside the do-catch block as shown below.

Swift try语句仅在它位于do-catch块中时才执行,如下所示。

do{
try userTest(age: -1, name: "")
} catch let error {
    print("Error: \(error)")
}

Below image shows the output of above program.

下图显示了上面程序的输出。

Alternatively we can do this:

或者,我们可以这样做:

do{
try userTest(age: -1, name: "")
}
catch UserDetailError.noValidName
{
    print("The name isn't valid")
}
catch UserDetailError.noValidAge
{
    print("The age isn't valid")
}
catch let error {
    print("Unspecified Error: \(error)")
}

初始化程序中的抛出错误 (Throwing Errors in Initializers)

We can add throws in the initializer in the following way.

我们可以通过以下方式在初始化器中添加throws

enum StudentError: Error {
    case invalid(String)
    case tooShort
}

class Student {
    var name: String?
    init(name: String?) throws {
        guard let name = name else{
            throw StudentError.invalid("Invalid")
        }
        self.name = name }

    func myName(str: String) throws -> String {

        guard str.count > 5
            else{
                throw StudentError.tooShort
        }

        return "My name is \(str)"
    }
}

Now to initialise the class we normally do the following, right?

现在初始化类,我们通常执行以下操作,对吗?

var s = Student(name: nil)
//compiler error

WRONG

错误

Since the intializer is throwing errors we need to append try keyword as shown below.

由于初始化器引发错误,因此我们需要追加try关键字,如下所示。

do{
var s = try Student(name: nil)
}
catch let error
{
    print(error)
}

//prints
//invalid("Invalid")

Let’s call the class function on the object too as shown below.

swift try example

我们也如下图所示在对象上调用类函数。

迅捷尝试,尝试吗? 并尝试! (Swift try, try? and try!)

  • Swift try is the most basic way of dealing with functions that can throw errors.

    Swift try是处理可能引发错误的函数的最基本方法。
  • try? is used to handle errors by converting the error into an optional value. This way if an error occurs, the function would return a nil and we known Optionals can be nil in Swift. Hence for try? you can get rid of do-catch block.

    尝试? 用于通过将错误转换为可选值来处理错误。 这样,如果发生错误,该函数将返回nil并且我们知道Optionals在Swift中可以为nil。 因此, try? 您可以摆脱do-catch块。
  • try! is used to assert that the error won’t occur. Should be only used when you’re absolutely sure that the function won’t throw an error. Like try?, try! works without a do-catch block.

    try! 用于断言该错误不会发生。 仅在绝对确定该函数不会引发错误时使用。 喜欢try? try! 在没有捕获块的情况下工作。
var t1 = try? Student(name: nil)
var t2 = try! Student(name: "Anupam")

That’s all for Swift error handling and swift try examples.

这就是Swift错误处理和Swift尝试示例的全部内容。

Reference: Apple Docs

参考: Apple Docs

翻译自: https://www.journaldev.com/19651/swift-error-handling-swift-try

swift 抛出错误

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值