I've seen that there is already a question on the difference between NSError
and Error
in Swift and I am aware of the differences. However, I do not understand the behavior of the code snippet below, since it compiles correctly. Swift's error handling mechanism requires that every do-catch block not appearing in a function with a throws clause to include one generic handler (either catch
with nothing else or a catch
for Error). However, it appears that using NSError
has the same effect. Does anybody here know the reason why? I've read in another question that "any ErrorType-conformant class can be casted to NSError. These features are described here in the docs.". However, the documentation pointed to by that answer did not clarify this point to me, since it focuses on Objective-C, which I am not using.
import Foundation
extension Int : Error {}
extension String : Error {}
func fErr() throws {
let a = Int(readLine()!)!
if a > 20 {
throw 42
} else {
throw "An error occurred"
}
}
func gErr() {
do {
try fErr()
} catch let e as NSError {
print(e)
}
}