Try-Catch Error Handling in JavaScript

Level 4219 keystrokes

This demonstrates throwing and catching errors with try-catch.

JavaScript code

// Function that throws an error for division by zero
1function divide(a, b) {
2 if (b === 0) {
// throw creates an error that stops execution
3 throw new Error("Cannot divide by zero");
4 }
5 return a / b;
6}
7
// try block contains code that might throw an error
8try {
// This succeeds: 10 / 2 = 5
9 console.log(divide(10, 2));
// This throws an error
10 console.log(divide(10, 0));
// catch block handles any thrown errors
11} catch (error) {
// error.message contains the error text
12 console.log("Error:", error.message);
13}

Output

5
Error: Cannot divide by zero
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 9
  • )× 9
  • ;× 5
  • ,× 4
  • .× 4
  • "× 4
  • {× 4
  • }× 4
  • =× 3
  • :× 1

More JavaScript examples at level 4

← JavaScript typing practice