swift异常处理_Swift中的错误处理程序

swift异常处理

Error handling highly contribute to the code quality. It also make programmer’s intention more visible. Swift these days evolved better to propagate and handle errors. This article is about to discuss some of the error handlers and their use and impact. Also, would spread some light on use in different configuration modes.

错误处理在很大程度上提高了代码质量。 这也使程序员的意图更加明显。 如今,Swift发展得更好,可以传播和处理错误。 本文将讨论一些错误处理程序及其使用和影响。 同样,在不同的配置模式下使用时也会散发出一些光芒。

Error is either programmer’s mistake or OS/IDE drawback and to respond or handle that unexpected behavior is Error Handling. Simple !! Let’s list some of the available Error handlers in swift:

错误要么是程序员的错误,要么是OS / IDE的缺点,而响应或处理意外行为就是错误处理。 简单! 让我们快速列出一些可用的错误处理程序:

  1. Throw, Try-Catch

    投掷,接球
  2. Assertion

    断言
  3. Precondition

    前提
  4. Fatal Error

    致命错误

These errors could be distinguish more as Programming and Runtime Error handlers. Programming errors are those which are logical mistakes or unhandled conditions. On the other way, Runtime errors caused by the OS/IDE/API failures.

这些错误可以更像是编程错误和运行时错误处理程序。 编程错误是指逻辑错误或未处理的情况。 另一方面,由OS / IDE / API故障引起的运行时错误。

In order to handle the Programming errors, swift offers assertion, precondition and fatal error handlers. On the other side try-catch as the legacy and effective way to handle the runtime errors. Swift allow the throw methods to help in try-catch techniques. Adding on this, swift also offers optional<T>, result<T> and try? (example of throw).

为了处理编程错误,swift提供了断言,前提条件和致命错误处理程序。 另一方面,try-catch是处理运行时错误的传统且有效的方法。 Swift允许使用throw方法来帮助进行try-catch技术。 除此之外,swift还提供可选的<T>,结果<T>并尝试? (抛出示例)。

To dig more into basic things, reach the official document — Swift Error Handlers

要深入研究基本内容,请访问官方文档-Swift Error Handlers

Throw, Try-Catch: The all time success method to handle the error, try-catch method also proposed in swift with throw. The throw generate an error instance of class Error. Throwing error indicates the exceptional in expectation to happen and break the normal flow to achieve the expectation. It has expression like:

Throw,Try-Catch :始终成功的方法来处理错误,try-catch方法也Swift地与throw一起提出。 抛出将生成错误类Error的错误实例。 投掷错误表示发生异常预期并破坏正常流量以达到预期。 它具有如下表达式:

Image for post

The method which is expected to be failed, should be define with throws keyword as postfix in the function definition. So with the help of do-try-catch pair the runtime errors can be handled well! Adding two more cents in this, Throw, try-catch is revoverable method.

预期会失败的方法应在函数定义中使用throws关键字作为postfix进行定义。 因此,借助do-try-catch对,可以很好地处理运行时错误! 在此添加两分钱, Throw,try-catch是可恢复的方法。

Why, where to use it? Yes, it should be considered when-

为什么在哪里使用呢? 是的,应该在以下情况下考虑使用-

  • Error is impossible to handle inside a method.

    错误是不可能在方法内部处理的。
  • Control flow needs to be changed

    控制流程需要更改
  • Multiple errors has to handle in a single catch method

    多个错误必须在单个catch方法中处理

Throw is always helpful when app is expecting input from different entities. Who may leads different type of input, null, data casting issue is expected to happen.

当应用程序期望来自不同实体的输入时,throw总是有帮助的。 可能由谁来领导不同类型的输入,空数据转换问题。

Optional, Try is another way to handle the small errors, or to avoid null values in the normal execution. It is best practice to use these when -

可选,尝试是另一种处理小错误或避免在正常执行中出现空值的方法。 最佳做法是在以下情况下使用这些:

  • Casting a variable to data type

    将变量转换为数据类型
  • Parsing APIs

    解析API
  • Read only computed properties

    只读计算的属性
  • Computed functions with throws

    带抛出的计算函数

Also, I want to agree here that, use of optional, try, force wrapping is totally debatable. Each developer can use it as of its best understanding.

另外,我想在这里同意,使用可选,尝试,强制包装是完全有争议的。 每个开发人员都可以根据自己的最佳理解来使用它。

Throw, try-catch can be shorten with only use of try? and try! and here you better know the result of ? & !.

抛出,仅使用try可以缩短try-catch? 尝试! 在这里您更好地知道的结果? &!。

Result represents success & failure with an error. Unlike Optional, it is more helpful and provide helpful context causing the failure. It associates with errors and have more information. It is useful when —

结果代表成功与失败,并带有错误。 与Optional不同,它更有用,并提供了导致失败的有用上下文。 它与错误相关,并具有更多信息。 当-

  • An error may occur in Asynchronous completion handlers. (Callbacks, API calls etc.)

    异步完成处理程序中可能会发生错误。 (回调,API调用等)
  • When success and failure both are considered as expected outputs.

    当成功和失败都被视为预期输出时。

Assertion: It helps in handling the Programming errors and test for conditions, which should happen only for wrong logic or code. For example: forget to set storyboardId, cell Identifiers etc. Assertions are active only for development mode and skipped in production. So in production developer must need to take care of fallback.

断言:它有助于处理编程错误和测试条件,这些条件仅应在错误的逻辑或代码下发生。 例如:忘记设置storyboardId,单元格标识符等。断言仅在开发模式下处于活动状态,而在生产中被跳过。 因此,在生产中,开发人员必须注意回退

Assert is the suitable tool to track down programming mistakes. It is useful in the conditions when there is no critical issue and app have alternate justifying action to perform other than termination. As it would crash the app only in development, so app must need to add fallback of failure in producttion. Adding code for analytic or crash report can help here to fix/detect the issue in upcoming release. Let check with example —

断言是跟踪编程错误的合适工具。 在没有严重问题并且应用程序有其他合理的措施要执行而不是终止的情况下,此功能很有用。 由于它将仅在开发中使应用程序崩溃,因此应用程序必须需要增加生产失败的后备。 添加用于分析或崩溃报告的代码可以在此处帮助修复/检测即将发布的问题。 让我们以示例检查一下—

Image for post

So in above example Student must have Id, and to validate that we have added check with the help of assertion. In above example same thing is handled by 2 different methods, developer can use any of them. Also, message is not required, it has default value as empty if developer don’t pass it. Again reminding that this assertion won’t work in production app, so better to use fallback code here.

因此,在上面的示例中,Student必须具有ID,并且要验证我们是否在断言的帮助下添加了检查。 在上面的示例中,同一件事由2种不同的方法处理,开发人员可以使用其中任何一种。 另外,消息不是必需的,如果开发人员不通过,则其默认值为空。 再次提醒此断言在生产应用程序中不起作用,因此最好在此处使用后备代码。

Precondition: This behave same as assert is. The only difference is that precondition will terminate the app in both develop and production. It also do not have any return type. If you can replace the keyword “assert” with “precondition” in above example, it would be perfect.

前提:此行为与assert相同。 唯一的区别是前提条件将在开发和生产中终止该应用程序。 它也没有任何返回类型。 如果您可以在上面的示例中将关键字“ assert”替换为“ precondition”,那将是完美的选择。

Preconditions are useful when —

在以下情况下,前提条件很有用:

  • Function needs arguments to consume, script has to run etc.

    函数需要使用参数,脚本必须运行等。

Fatal Error: Yeah, as its name suggest it is hand grenade for the app. It terminate the app unconditionally. It should only be used for the errors that put an app to state where termination is the only reasonable action. Unlike other handlers it has return type “never” so that can be used where errors has nothing to return.

致命错误 :是的,顾名思义,它是该应用程序的手榴弹。 它无条件终止应用程序。 它仅应用于将应用程序声明为终止是唯一合理的操作的错误。 与其他处理程序不同,它的返回类型为“从不”,因此可以在没有错误返回的地方使用。

So while comparing with other handlers, fatalError add failure messages to crash reports and others won’t.

因此,与其他处理程序进行比较时,fatalError将失败消息添加到崩溃报告中,而其他人则不会。

Fatal Errors are suggested to use only when —

建议仅在以下情况下使用致命错误:

  • Error is critical

    错误至关重要
  • Don’t have anything to return.

    没有任何退货。
Image for post

In above example, I have shown both methods how to use fatalError in code. As here, function is expecting a cell to return but programming mistake would leads to no cell there. So the return and error can handle with fatalError.

在上面的示例中,我展示了两种方法如何在代码中使用fatalError。 如此处所示,函数期望一个单元格返回,但是编程错误将导致那里没有任何单元格。 因此,可以使用fatalError处理返回和错误。

Swift error handling strategies can be categorized into:

Swift错误处理策略可以分为以下几类:

  • recoverable: Optional, Result, throw;

    可恢复的: OptionalResultthrow

  • and non-recoverable: assert(), precondition(), fatalError().

    和不可恢复的: assert()precondition()fatalError()

Non-recoverable strategies are generally more appropriate for dealing with logical errors; recoverable are for runtime errors. Picking the most sensible strategy contributes to code quality and makes programmer intent more clear.

不可恢复策略通常更适合处理逻辑错误; 可恢复是针对运行时错误。 选择最明智的策略有助于提高代码质量,并使程序员的意图更加清晰。

Feedback is appreciated, anything under the Milkyway.

对于银河系下的任何事物,您都可以提供反馈。

Happy Coding!!!

快乐编码!

翻译自: https://medium.com/dev-genius/error-handlers-in-swift-dce7153d9fe7

swift异常处理

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值