liveBook · Manning

Try-catch statement

As explained in Functional Programming in JavaScript

A control-flow structure that handles exceptions by enclosing risky code in a try block and handling thrown errors in a catch block.

Use a try-catch statement when code may fail, such as server communication, null-property access, or a third-party function that throws. The try block encloses unsafe code; catch receives an Error object with details and provides a place to recover. section 5.1

Handling a missing student

Calling findStudent with an unknown identifier can throw an exception. Wrapping the call lets the program report the error instead of stopping without handling it. section 5.1

try {
   // code that might throw an exception in here
}
catch (e) {
   // statements to handle any exceptions
   console.log('ERROR' + e.message);
}

A minimal structure separates risky code from the statements that handle its exception. section 5.1

Imperative try-catch handling becomes difficult when errors must be abstracted, composed, or chained. Throwing also creates an additional exit path, conflicting with predictable functional design. section 5.1

How Functional Programming in JavaScript covers it

How deep it goes
Explains the blocks, runtime halt, stack trace, Error object, and recovery role, but stops before functional alternatives.
Examples
Uses findObject, findStudent, missing identifiers, and nested fallback lookups as error-handling examples.
What it assumes
Assumes JavaScript functions that may throw and teaches the basic try and catch structure from there.
What you can do after
Apply it via JavaScript by enclosing risky calls and handling thrown Error objects.
How it connects
Connects exceptions with Error objects, stack traces, function composition, and referential transparency.

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 Functional Programming in JavaScript. The section links point to the parts of the book it draws on.