ios swift_iOS Swift中的错误处理

ios swift

We use error handling with do-try-catch in swift to respond to recoverable errors . It gives us great control over different fault scenarios that might occur in your code , such as user inputting a wrong username and password .

我们将错误处理与do-try-catch一起使用,以Swift响应可恢复的错误。 它使我们可以很好地控制代码中可能发生的不同故障情况,例如用户输入了错误的用户名和密码。

Further we will see in this article :

我们还将在本文中看到:

  • Why “throw” and “catch” errors

    为什么“抛出”和“捕获”错误
  • Why use syntax do-try-catch

    为什么使用语法do-try-catch
  • How you can create your own custom errors types

    如何创建自己的自定义错误类型
  • Different useful scenarios for using try? and try!

    使用try的不同有用方案? 尝试!

为什么“抛出”和“捕获”错误? (WHY “throw” and “catch” Errors?)

In iOS development , not all errors are bad . Some errors are part of an app’s lifecycle , such as a “Insufficient funds” message when you try to pay with your credit card. These kinds of errors are recoverable. They can be caught, handled ,and responded to appropriately.

在iOS开发中,并非所有错误都是不好的。 某些错误是应用程序生命周期的一部分,例如当您尝试使用信用卡付款时出现“资金不足”消息。 这些类型的错误是可恢复的。 他们可以被捕获,处理和适当地响应。

Examples :

例子 :

  • An ATM displays “Incorrect PIN code” when you try to withdraw money

    尝试取款时,ATM机显示“ PIN码不正确”
  • Your car shows a “Fuel low” indicator light as you try to start the engine

    尝试启动发动机时,汽车会显示“燃油不足”指示灯
  • An authentication attempt for an API returns “Wrong username/password”

    API的身份验证尝试返回“错误的用户名/密码”

You can recover from these errors by displaying an alert message, or doing something else. Your credit card gets blocked after 3 failed attempts , for example . Your car can point you to the nearest fuel pump station when you are out of gas . And you can try a difference username and password .

您可以通过显示警报消息或执行其他操作来从这些错误中恢复。 例如,在3次失败尝试后,您的信用卡就会被冻结。 没油的时候,您的车可以指引您到最近的加油站。 您可以尝试使用其他用户名和密码。

Swift has a class for supporting error handling with the do-try-catch block of code . do-try-catch has the same king of control over your app as if and return .

Swift有一个类,用于使用do-try-catch代码块支持错误处理。 do-try-catch对您的应用程序具有相同的控制权,就好像和return一样。

For example :

例如 :

With do-try-catch you can handle errors that have been thrown with throw . We’ll get into this syntax later on. What’s interesting for now, is the throwing and catching principle.

使用do-try-catch,您可以处理throw引发的错误。 稍后我们将介绍这种语法。 现在有趣的是投掷和接球原理。

Swift中的抛出错误 (Throwing Error in Swift)

Suppose this scenario that should result in an error occurse in your code , you can throw an error like this :

假设应该在代码中发生错误的这种情况下,您可以引发如下错误:

if fuel < 1000 {     
throw RocketError.insufficientFuel
}

In the above code , the throw keyword is used to throw an error of type RocketError.insufficientFuel when the fuel variable is less than 1000 .

在上面的代码中,当加油变量小于1000时,throw关键字用于引发RocketError.insufficientFuel类型的错误。

Imagine we are trying to fire a a rocket :

想象一下,我们正在尝试发射火箭:

func igniteRockets(fuel:Int, astronauts: Int) throws {
if fuel < 1000 {
throw RocketError.insufficientFuel
}
else if astronauts < 3 {
throw RocketError.insufficientAstronauts(needed : 3)
} print("3....2...1...Ignition !!!LIFTOFF!!!!")
}

In the above function igniteRockets(fuel:astronauts:) will only ignite the rockets if fuel is greater or equal to the 1000 and if there are at least 3 astronauts on board . The igniteRoackets(…) function is also marked with the throws keyword. This keyword indicates to whoever calls this function that errors need to be handled. Swift forces us to handle errors (or rethrow them), which means you can’t accidentally forget it!

在上述函数中,igniteRockets(fuel:astronauts :)仅在燃料大于或等于1000且船上至少有3位宇航员时才点燃火箭。 igniteRoackets(…)函数也用throws关键字标记。 此关键字向任何调用此函数的人指示需要处理错误。 Swift迫使我们处理错误(或将错误回去),这意味着您不会偶然忘记它!

In above code we are using an error type called RoacketError : AS

在上面的代码中,我们使用称为RoacketError的错误类型:AS

enum RocketError: Error {
case insufficientFuel
case insufficientAstronauts(needed: Int)
case unknownError
}

The enumeration extends Error and defines three types of error: .insufficientFuel , insufficientAstronauts(needed) and .unknownError.

枚举扩展了Error并定义了三种错误类型:.insufficientFuel,不足Astronauts(needed)和.unknownError。

Defining your own error types if very useful , because you can be very clear about what these errors mean in your code .

定义自己的错误类型(如果非常有用的话),因为您可以非常清楚这些错误在代码中的含义。

The throw keyword has the same effects as the return keyword . So when throw is executed , execution of the function stops at that point and the thrown error is passed to the caller of the function .

throw关键字与return关键字具有相同的效果。 因此,当执行throw时,函数的执行将在此时停止,并且将引发的错误传递给函数的调用者。

使用try-try-catch处理错误 (Handling Errors With Do-Try-Catch)

Now we can use error handling to appropriately respond to these error scenarios . Error handling is swift is done with a so called do-try-catch block .

现在,我们可以使用错误处理来适当地响应这些错误情况。 通过所谓的do-try-catch块可以快速完成错误处理。

See:

看到:

do { 
try igniteRockets(fuel: 5000, astronauts: 1)
} catch {
print(error)
}

You can also respond to error cases individually :

您还可以分别对错误情况进行响应:

do {
try igniteRockets(fuel: 5000, astronauts: 1)
} catch RocketError.insufficientFuel {
print("The rocket needs more fuel to take of !")
} catch RocketError.insufficientAstronauts(let needed){
print("You need at least \(needed) astronauts ...")
}

使用“ try?”将错误转换为可选内容 (Converting Errors To Optionals With “try?”)

The purpose of error handling is to explicitly determine what happens when an error occurs. This allows you to recover from errors, instead of just letting the app crash.

错误处理的目的是明确确定发生错误时发生的情况。 这使您可以从错误中恢复,而不仅仅是让应用程序崩溃。

In some cases, you don’t care much about the error itself. You just want to receive value from a function, for example. And if an error occurs, you’re OK with getting nil returned.

在某些情况下,您不太关心错误本身。 例如,您只想从一个函数接收值。 如果发生错误,则可以返回nil

You can do this with the try? keyword. It combines try with a question mark ?, in a similar fashion as working with optional . When you use try?, you don’t have to use the complete do-try-catch block.

您可以try? 关键词。 它结合try和问号? ,类似于使用optional的方式。 什么时候使用try? ,则不必使用完整的do-try-catch块。

Here’s an example:

这是一个例子:

let result = try? calculateValue(for: 42)

Imagine the calculateValue(for:) function can throw errors, for example if its parameter is invalid. Instead of handling this error with do-try-catch, we’re converting the returned value to an optional.

想象一下calculateValue(for:)函数会引发错误,例如,如果其参数无效。 而不是使用do-try-catch处理此错误,我们将返回的值转换为optional

One of two things will now happen:

现在将发生两件事之一:

  1. The function does not throw an error, returns a value, which is assigned to result

    该函数不会引发错误,返回一个值,该值被分配给result

  2. the function throws an error, and does not return a value, which means that nil is assigned to result

    该函数将引发错误,并且不返回值,这意味着将nil分配给result

Handling errors this way means you can benefit from syntax specific to optionals, such as ?? and optional binding. Like this:

以这种方式处理错误意味着您可以受益于特定于可选内容的语法,例如?? 和可选的绑定。 像这样:

if let result = try? calculateValue(for: 99) {
// Do something with non-optional value "result"
}

And using nil-coalescing operator ?? to provide a default value:

并使用nil-coalescing运算符 ?? 提供默认值:

let result = try? calculateValue(for: 123) ?? 101

It’s compelling to use try? to ignore or silence errors, so don’t get into the habit of using try? to avoid having to deal with potential errors. Error handling with do-try-catch is a feature for a reason, because it generally makes your code safer. Avoiding to recover from errors only leads to bugs later on.

try?很引人注目try? 忽略或使错误静音,所以不要养成使用try?的习惯try? 以避免必须处理潜在的错误。 使用do-try-catch错误处理是一项功能,这是有原因的,因为它通常会使您的代码更安全。 避免从错误中恢复只会在以后导致错误。

通过“ try!”禁用错误处理 (Disabling Error Handling With “try!”)

You can also disable error handling entirely, with try!.

您也可以使用try!完全禁用错误处理try!

Just as the try? keyword, the try! syntax combines try with an exclamation mark !, in a similar fashion to force unwrapping optionals When you use try!, you don’t have to use the complete do-try-catch block.

就像try? 关键字, try! 语法结合try和感叹号! ,以类似的方式强制展开可选内容try! ,则不必使用完整的do-try-catch块。

Unlike try?, which returns an optional value, the try! syntax will crash your code if an error occurs. There are two distinct scenarios in which this is useful:

不像try? ,它返回一个可选值,请try! 如果发生错误,语法会使您的代码崩溃。 在两种不同的情况下,这很有用:

  • Use try! when your code could impossibly lead to an error, i.e. when it’s 100% certain that an error will not occur

    使用try! 当您的代码可能会导致错误时,即100%确定不会发生错误时

  • Use try! when you can’t recover from an error, and it’s impossible to continue execution beyond that point

    使用try! 当您无法从错误中恢复时,并且无法继续执行超出该点的操作

Imagine you’re coding an app that has a database file embedded in it. The function to load the database throws an error when the database is corrupted. You can safely use try! to load that database into memory, because when the database is corrupted, the app won’t be usable anyway.

假设您正在编码的应用程序中嵌入了数据库文件。 数据库损坏时,加载数据库的功能将引发错误。 您可以放心使用try! 将该数据库加载到内存中,因为当数据库损坏时,该应用程序将始终无法使用。

MY LINKEDIN : linkedin.com/in/my-pro-file

我的链接: linkedin.com/in/my-pro-file

您可能感兴趣的主题 (Topics You May Interested IN)

翻译自: https://medium.com/swlh/error-handling-in-ios-swift-6abce33a40e7

ios swift

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值