Home > Mobile >  Why try/catch block doesn't cover all the runtime exceptions?
Why try/catch block doesn't cover all the runtime exceptions?

Time:01-12

What I try to do is

...
let path: URL? = URL(string: "")
    
    do {
        let data = try Data(contentsOf: path!)
    }
    catch {
        print("ERROR: \(error)")
    }
...

I know that this code won't work, but what I expect is to catch the error in the catch block instead I get a runtime exception and crash.

CodePudding user response:

try this

..
if let path = URL(string: "someStringForUrl") {
    
    do {
        let data = try Data(contentsOf: path)
    }
    catch {
        print("ERROR: \(error)")
    }
}
...

CodePudding user response:

You never reach the try, so you never reach the catch. Before any of that can happen, the path! forced unwrap fails and crashes the app.

(Crashing the app is a runtime exception, which is a completely different thing from the Swift try/catch mechanism. It doesn't not "cover all the runtime exceptions"; it doesn't cover any runtime exceptions. You're confusing apples with elephants; they are totally unrelated. Runtime exceptions are not thrown-caught Error objects, and vice versa.)

  •  Tags:  
  • Related