1

I am new to swift. I am learning to use do-catch. I created the following situation. When assigning a value of nil to an option, an error should be reported when forced unpacking the value of nil. Isn't do-catch used to detect runtime errors? I want to know why do catch fails to catch this error.

func canThrowAnError() throws -> Int {
    let a = 1
    let b = 2
    var c: Int? = a + b
    c = nil
    let d = c!
}

do {
    try canThrowAnError()
} catch {
    print("catch error")
}

enter image description here

Sulthan
  • 128,090
  • 22
  • 218
  • 270
ink
  • 519
  • 6
  • 19
  • 3
    do-catch can catch errors created by `throw`, not fatal errors. You cannot catch `nil` errors. – Sulthan Nov 26 '21 at 08:19
  • [Here](https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html) is a good article on error handling from The Swift Programming Language book – Joakim Danielson Nov 26 '21 at 08:27
  • Also [Catch any error, specially unexpectedly found nil in swift](https://stackoverflow.com/questions/35007792/catch-any-error-specially-unexpectedly-found-nil-in-swift) – Dalija Prasnikar Nov 26 '21 at 08:30
  • @Sulthan Thank you Sulthan, I am a swift novice, I think the do-catch method in swift is not elegant. In python, try: except: can automatically catch errors without executing throw, and python also has the raise keyword, similar to throw – ink Nov 26 '21 at 09:01
  • 1
    @ink You are thinking wrong. In Swift the errors are actually safer. Using `!` is a dangerous operation that should be used rarely. You can rarely recover from such an exception and it's pointless to try. – Sulthan Nov 26 '21 at 09:25

0 Answers0