Swift 2.0 do-try-catch 和常规 Java/C#/C++ 异常有什么区别 [英] What is the difference between Swift 2.0 do-try-catch and regular Java/C#/C++ exceptions

查看:32
本文介绍了Swift 2.0 do-try-catch 和常规 Java/C#/C++ 异常有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 2.0 似乎已经从传统的 ObjC(返回 NSError)和 Swift 1.X(成功/失败选项)的运行时错误处理约定转变为与 Java/C#/等语言中的异常处理非常相似的东西.C++/等

It seems that Swift 2.0 has changed from traditional ObjC (NSError returning) and Swift 1.X (Success/Failure optionals) conventions of runtime error handling, to something that looks very similar to exception handling in languages like Java/C#/C++/etc.

Apple 传统上强调使用NSError 而不是为运行时错误抛出 NSException(相对于程序员错误),因为 NSException 堆栈展开可能会导致默认 ObjC 编译器设置的内存泄漏.

Apple has traditionally emphasized use of NSError instead of throwing NSException for runtime errors (vs programmer errors), as NSException stack unwinding could cause memory leaks with default ObjC compiler settings.

然而,现在他们设计了一些看起来与传统异常非常相似的东西.我的问题是:

Now they have however devised something that looks very, very similar to traditional exceptions. My question is:

除了命名法(错误与异常)和语法(do-catch,而不是try-catch, 尝试在方法调用之前使用,等等).

Are there any real differences between Swift 2.0 error handling and traditional exception handling beside nomenclature (error vs exception) and syntax (do-catch, instead of try-catch, try used before method call, etc).

推荐答案

我发现了 3 个主要差异:

There are 3 major differences I have found:

  1. 没有必要列出一个函数可以抛出的所有错误,只需要一个throws关键字即可.

使用这些错误时没有明显的减速,而 Java 和其他语言需要构造一个 Exception 对象并展开堆栈.在 Swift 中,throws 关键字可以被视为返回一个 Either 对象的函数,其中一个是原始返回类型,另一个是 ErrorType代码>值.

There is no significant slowdown when using these errors, while Java and other languages need to construct an Exception object and unwind the stack. In Swift a throws keyword can be viewed as the function returning an Either-object, with one being the original return type, and the other being an ErrorType value.

在 Swift 中,所有错误都需要处理或声明为抛出,不可能从没有声明它正在抛出错误的方法中获取错误.(在 Java 术语中,所有错误都是检查异常")

In Swift all errors need to be handled or declared to be thrown, it is impossible to get an error from a method that does not state it is throwing an error. (in Java terms, all errors are "checked exceptions")

这篇关于Swift 2.0 do-try-catch 和常规 Java/C#/C++ 异常有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆