Skip to content
dreamcode
dreamcode
Map
Error handling
Lesson 31 of 48
+15 XP on finish
JAVASCRIPT CLIMBSChapter 6 · JS Async and Errors

Catching errors with try-catch

Use try...catch to intercept errors. You can throw custom errors using the throw statement.

Worked example

How it reads

  • throw new Error(...) creates and fires an error object
  • catch (error) receives the thrown error
Cloud tip: You can also use a finally block to execute code regardless of whether an error was thrown.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Write checkAltitude(n) that throws new Error("too low") when n is below 100. Call it with 40 inside try...catch and log error: too low.

Press Run to check your work.