0
0
Javascriptprogramming~5 mins

Throwing errors in Javascript

Choose your learning style9 modes available
Introduction

Throwing errors helps your program stop and tell you when something goes wrong. It makes problems clear so you can fix them.

When a user enters wrong information in a form.
When a file your program needs is missing.
When a calculation gets an unexpected value.
When a function gets bad input it can't handle.
Syntax
Javascript
throw new Error('Your error message here');

throw stops the program and sends an error.

Error is a built-in way to create an error message.

Examples
This stops the program and shows the message 'Something went wrong!'.
Javascript
throw new Error('Something went wrong!');
You can throw a string directly, but using Error is better for details.
Javascript
throw 'This is a simple error string';
You can throw different error types like TypeError for specific problems.
Javascript
throw new TypeError('Wrong type!');
Sample Program

This program checks if a person is old enough. If not, it throws an error. The error is caught and shown nicely.

Javascript
function checkAge(age) {
  if (age < 18) {
    throw new Error('You must be at least 18 years old.');
  }
  return 'Access granted';
}

try {
  console.log(checkAge(16));
} catch (error) {
  console.log('Error caught:', error.message);
}

console.log(checkAge(20));
OutputSuccess
Important Notes

Always use try...catch to handle errors so your program doesn't crash unexpectedly.

Use clear messages in errors to help understand what went wrong.

Summary

Throwing errors stops the program when something is wrong.

Use throw new Error('message') to create errors.

Catch errors with try...catch to handle them safely.