Concept Flow - Error protocol conformance
Define Error Type
Conform to Error Protocol
Throw Error
Catch Error
Handle Error
This flow shows how to define a custom error type by conforming to the Error protocol, then throwing and catching that error.
enum MyError: Error { case badInput } func check(input: Int) throws { if input < 0 { throw MyError.badInput } }
| Step | Action | Condition | Result | Output |
|---|---|---|---|---|
| 1 | Call check(input: 5) | 5 < 0? | False | No error thrown |
| 2 | Function returns normally | - | - | - |
| 3 | Call check(input: -3) | -3 < 0? | True | Throw MyError.badInput |
| 4 | Error caught in catch block | - | - | Handle error |
| Variable | Start | After Step 1 | After Step 3 | Final |
|---|---|---|---|---|
| input | - | 5 | -3 | -3 |
| errorThrown | nil | nil | MyError.badInput | MyError.badInput |
Define an enum or struct conforming to Error protocol. Use 'throw' keyword to throw errors. Use 'try' to call throwing functions. Catch errors with 'do-catch' blocks. Only Error-conforming types can be thrown.
Error protocol in Swift?Error protocol?: Error after its name.enum FileError: Error {
case notFound
case unreadable
}
func readFile(_ name: String) throws -> String {
if name == "missing.txt" {
throw FileError.notFound
}
return "File content"
}
do {
let content = try readFile("missing.txt")
print(content)
} catch FileError.notFound {
print("File not found error caught")
} catch {
print("Other error")
}FileError.notFound when the filename is "missing.txt".FileError.notFound and prints "File not found error caught".enum LoginError: Error {
case invalidUsername
case invalidPassword
}
func login(user: String, password: String) throws {
if user.isEmpty {
throw LoginError.invalidUsername
} else if password.isEmpty {
throw LoginError.invalidPassword
}
}
try login(user: "", password: "1234")try but outside a do-catch block or without try? or try!, causing a compile-time error.DatabaseError that conforms to Error and includes cases for connectionFailed, queryFailed, and timeout. Additionally, you want to add a computed property message that returns a user-friendly description for each case. Which of the following is the correct implementation?message uses a switch on self to return descriptive strings for each case.Pass the test and this pattern moves unknown