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.