Concept Flow - Try! for forced unwrap
Call try! expression
Does expression throw error?
Return value
Continue execution
The try! keyword runs a throwing expression and forces unwraps the result. If an error occurs, the program crashes immediately.
func canThrow() throws -> String { return "Success" } let result = try! canThrow() print(result)
| Step | Action | Expression Result | Error Thrown? | Outcome | Program State |
|---|---|---|---|---|---|
| 1 | Call canThrow() with try! | "Success" | No | Return "Success" | Program continues |
| 2 | Assign result = "Success" | "Success" | No | result holds "Success" | Program continues |
| 3 | Print result | "Success" | No | Output: Success | Program continues |
| 4 | End | - | - | - | Program ends normally |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| result | nil | nil | "Success" | "Success" |
try! runs a throwing function and forces unwraps the result. If no error, returns value normally. If error occurs, program crashes immediately. No need for do-catch with try!. Use carefully to avoid runtime crashes.