liveBook · Manning

Try-catch statement

As explained in Elixir in Action, Third Edition

A try construct is an Elixir control-flow construct for explicitly catching and handling exceptions and other error outcomes.

Use a try construct to localize runtime failures instead of letting them disturb unrelated work. Code in the do block runs normally; a catch transfers control when an error, exit, or throw occurs. The catch receives a type—:error, :exit, or :throw—and an error-specific value, both matched as patterns. The construct returns the last value from either block, and an after clause runs cleanup code. section 8.1.2 section 9.4

try do
 ...
catch error_type, error_value ->
 ...
end

Use the basic form to execute code and match the kind and value of a caught runtime outcome. section 8.1.2

Preserving critical process state

A critical server callback can transform state inside try and return an error response while retaining the original state when work fails: catch _, _ -> {:reply, {:error, reason}, state}. This can preserve consistency through immutable transformations, but it does not replace supervision: an un-interceptable :kill exit still requires a recovery plan. section 9.3.1 section 9.4

How Elixir in Action, Third Edition covers it

How deep it goes
Explains error categories, pattern matching, return values, cleanup, and state rollback, then defers unrecoverable crashes to supervision.
Examples
Demonstrates raising, throwing, exiting, pattern-matched results, cleanup clauses, and defensive handle_call state transformations.
What it assumes
Assumes familiarity with Elixir processes, callback state, immutable transformations, and supervision hierarchies.
What you can do after
Diagnose and handle selected runtime outcomes while returning controlled results or preserving prior process state.
How it connects
Connects exception handling with processes, immutable data structures, fault tolerance, and supervision trees.

Also explained in

Compare how 10 books explain try-catch statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.