try...catch

A statement that runs code in a try block and, if that code throws an exception, runs a catch block instead of crashing.

In more detail

Most languages, including JavaScript, TypeScript, Java and C#, provide it, often with a finally block that always runs. Catching lets a program recover or report the problem clearly; code should catch only errors it can actually handle.

Examples

The layer registry lesson wraps an illegal registration in try/catch and records that the layer inversion was rejected.
In the browser: Aborted work, storage quota errors and invalid JSON all throw, so resilient code wraps them in try...catch and falls back sensibly.
try { read(); } catch (IOException ex) { System.out.println(ex.getMessage()); }
React error boundaries do not catch errors in event handlers or async code, so wrap those in try...catch yourself.

Related terms

Taught in

References

Certification courses