Topic
Error Handling
panic! stops your program immediately when something goes wrong. Result lets you handle errors and keep running. Learn both and when to use each.Quick Reference
| Concept | What it means |
|---|---|
| panic! | Prints an error message, cleans up memory, and exits the program immediately. |
| Result<T, E> | An enum with two variants: Ok(T) when things work, Err(E) when they fail. |
| Ok(value) | The success variant of Result. Wraps the value you get back when nothing went wrong. |
| Err(message) | The failure variant of Result. Wraps an error value describing what went wrong. |
| match on Result | The standard way to handle both Ok and Err cases without crashing. |
| unwrap() | Extracts the value from Ok. Panics if the variant is Err. Only use when you are certain it will succeed. |
| ? operator | Shorthand for propagating errors. Returns the Err early instead of panicking. Can only be used in functions that return Result. |
| Term | What it means | When you use it |
|---|---|---|
| panic! | Stops the program immediately with a message and cleans up memory. There is no recovering from a panic. | When something has gone so wrong that the program cannot safely continue, like an impossible state or a violated invariant. |
| Result<T, E> | An enum with Ok for success and Err for failure. Lets the caller decide what to do with errors. | Any time a function can fail and the caller should decide what happens next. |
| Ok(value) | The success variant of Result. Wraps the returned value when everything went right. | When a function completes successfully and needs to pass a value back to the caller. |
| Err(message) | The failure variant of Result. Wraps an error description when something went wrong. | When a function fails and needs to tell the caller what went wrong instead of panicking. |
| match on Result | Handles both Ok and Err with separate code paths. The compiler requires both arms. | Every time you call a function that returns Result and want to act differently on success vs failure. |
| unwrap() | Extracts the value from Ok in one step. Panics if the variant is Err. | Only when you are certain the result will be Ok, such as parsing a hard-coded literal you wrote yourself. |
| ? operator | Unwraps Ok or returns Err early from the current function. Shorthand for writing match on every call. | Inside functions that return Result, when you want errors to propagate up automatically without writing match. |