Error Handling

Errors are a fact of life in software, so Oxide has a number of features for handling situations in which something goes wrong. In many cases, Oxide requires you to acknowledge the possibility of an error and take some action before your code will compile. This requirement makes your program more robust by ensuring that you'll discover errors and handle them appropriately before deploying your code to production!

Oxide groups errors into two major categories: recoverable and unrecoverable errors. For a recoverable error, such as a file not found error, we most likely just want to report the problem to the user and retry the operation. Unrecoverable errors are always symptoms of bugs, such as trying to access a location beyond the end of an array, and so we want to immediately stop the program.

Most languages don't distinguish between these two kinds of errors and handle both in the same way, using mechanisms such as exceptions. Oxide doesn't have exceptions. Instead, it has:

  • The type Result<T, E> for recoverable errors
  • The panic! macro that stops execution when the program encounters an unrecoverable error
  • Nullable types T? for values that may or may not exist
  • Ergonomic operators ?? and !! for working with nullable values

This chapter covers:

  1. Unrecoverable Errors with panic! - When to stop the program entirely
  2. Recoverable Errors with Result - When to give callers a chance to handle failure
  3. Working with Nullable Types - Using T?, ??, and !! effectively
  4. To panic! or Not to panic! - Guidelines for choosing the right approach

Oxide's Error Handling Philosophy

Oxide inherits Rust's philosophy of making error handling explicit and type-safe. However, Oxide adds ergonomic operators that make common patterns more concise:

OxideRust EquivalentPurpose
T?Option<T>Value that might be absent
nullNoneAbsence of a value
x ?? defaultx.unwrapOr(default)Provide fallback for nullable
x!!x.unwrap()Force unwrap (panics if null)
x?x?Propagate errors (unchanged)

These operators make error handling more readable while maintaining the same safety guarantees as Rust.