Consider the following Swift code that defines an error and uses do-catch to handle it. What will be printed?
enum MyError: Error { case badInput } func testError() throws { throw MyError.badInput } do { try testError() print("No error") } catch MyError.badInput { print("Caught badInput error") } catch { print("Caught some other error") }
Think about which error is thrown and which catch block matches it.
The function testError() throws MyError.badInput. The do-catch block catches this specific error in the first catch clause and prints "Caught badInput error".
Given this Swift code, what error will be raised at runtime?
struct NotAnError {} func throwSomething() throws { throw NotAnError() } try? throwSomething()
Check if the thrown type conforms to the Error protocol.
In Swift, only types conforming to the Error protocol can be thrown. Since NotAnError does not conform, the compiler will raise an error.
Examine the code below. Why does it fail to compile?
enum CustomError: Error { case errorOne } func mightThrow(_ flag: Bool) throws { if flag { throw "Error occurred" } } try? mightThrow(true)
Look at the type being thrown inside the function.
The code tries to throw a String, but String does not conform to Error. Only types conforming to Error can be thrown.
Which of the following Swift types correctly conforms to the Error protocol?
Remember that to be throwable, a type must explicitly conform to Error.
Only option D explicitly declares conformance to Error. The others do not conform and thus cannot be thrown.
Analyze the following Swift code. What will it print?
enum NetworkError: Error { case timeout case serverError(code: Int) } func fetchData() throws { throw NetworkError.serverError(code: 500) } do { try fetchData() } catch NetworkError.timeout { print("Timeout occurred") } catch NetworkError.serverError(let code) where code >= 500 { print("Server error with code \(code)") } catch { print("Other error") }
Check the thrown error and the pattern matching in the catch clauses.
The function throws NetworkError.serverError(code: 500). The second catch matches this case with a where clause checking code >= 500, so it prints "Server error with code 500".