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

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

问题描述

似乎Swift 2.0已经从运行时错误处理的传统ObjC(NSError返回)和Swift 1.X(成功/失败可选)约定转变为类似于Java / C#/ C ++ / etc。

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 for运行时错误 (与程序员错误),因为 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:

除了命名(错误vs异常)和之间,Swift 2.0错误处理和传统异常处理之间是否存在真正的区别>语法(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).

推荐答案

我发现有三个主要的区别:

There are 3 major differences I have found:


  1. 没有必要列出一个函数可以抛出的所有错误,只有一个

  1. It is not necessary to list all errors a function can throw, only a throws keyword is needed.

使用这些错误时没有明显的放缓,而Java和其他语言需要构造一个异常对象并展开堆栈。在Swift中, throws 关键字可以被视为返回一个的两个对象,其中一个是原始返回类型,另一个是 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天全站免登陆