Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

error handling - What is the difference between Swift 2.0 do-try-catch and regular Java/C#/C++ exceptions

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 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:

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are 3 major differences I have found:

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

  2. 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.

  3. 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")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...