⚡ JavaScript

معالجة الأخطاء والاستثناءات في JavaScript (Node.js): دليل شامل

Here is the translated HTML article in English, following all the specified rules. ```html

What is it and why? (a real-life analogy)

Imagine you are the captain of a spaceship. Your ship is flying to a distant star. Suddenly, a red light flashes on the dashboard: "Error! Engine overheating!" What will you do?

  • Option 1 (bad): You ignore the light. The ship explodes. The program "crashes".
  • Option 2 (good): You press the "Emergency Cooling" button. The engine cools down, the flight continues. The program "handled the error".
  • Option 3 (excellent): You not only turn on the cooling but also write in the logbook: "Warning! Engine #3 overheated. Cause: meteor shower. Measures taken." The program "logged the error".

In programming, an error (exception) is that same red light. It says: "Something went wrong! Can't continue working, urgent measures needed!"

Error handling is a set of tools that allow the program not to "explode" (not crash), but to gracefully solve the problem: inform the user what happened, try to fix the situation, or at least save data and terminate correctly.

Important: Errors are not always bad. They are signals. A good programmer is not the one who has no errors, but the one who knows how to catch them and react to them correctly.

In real life, we constantly handle errors:

  • Dialed a number — "Subscriber is unavailable." You don't throw the phone out the window, but wait for a dial tone or send an SMS.
  • Entered the wrong password — the site doesn't crash, but says: "Incorrect password, try again."
  • Opened a door — it's locked. You take out the key, instead of breaking the door down.

In JavaScript (especially in Node.js, where code runs on the server), error handling is a matter of survival. If the server crashes due to one error, all users will be left without the site. That's why we learn to catch errors.

Theory: how it works internally

Let's look "under the hood" of JavaScript and see how the error mechanism works.

Call Stack

Imagine a stack of plates. When a program calls a function, it puts a new plate on the stack. When the function finishes, the plate is removed. If an error occurs in a function, JavaScript looks at the top plate. If there is no "trap" for the error there, it removes that plate and looks at the next one. And so on until the very bottom. If there is no trap at the bottom either, the program crashes.

Error Types in JavaScript

All errors are objects. They have a name and a message. The most popular ones are:

Error Type When it occurs Example
ReferenceError Accessed a variable that doesn't exist console.log(a) (a is not declared)
TypeError Trying to do something with data of the wrong type null.name (null has no properties)
SyntaxError Language syntax is violated (typo in code) if (true {} (missing parenthesis)
RangeError Out of valid range new Array(-1) (negative array length)
URIError Incorrect use of URI handling functions decodeURI('%')

How JavaScript "throws" an error

When something bad happens, JavaScript creates an error object and throws it. It's like tossing a hot potato into the air — someone has to catch it, otherwise it will fall and break.

We can also throw errors manually using the throw command. This is useful when we ourselves want to say: "Stop! Can't work further!"

Syntax in JavaScript (Node.js): all forms and variations

The main tool for catching errors is the try...catch...finally construct. Let's break it down piece by piece.

Basic construct: try...catch

try {
    // Here we write code that might break
    // If an error occurs, the try execution is interrupted
    // and control passes to catch
} catch (error) {
    // The error object ends up here
    // Here we decide what to do: inform the user,
    // log it, try another method
}

Adding finally

The finally block ALWAYS executes — whether there was an error or not. It's like cleaning up after a party: even if everything went perfectly, you still take out the trash.

try {
    // Try to do something
} catch (error) {
    // Catch the error
} finally {
    // This code will execute in any case
    // For example: close a file, disconnect from the database
}

Throwing your own errors: throw

We can create our own error and "throw" it:

throw new Error('My error message');
// You can use different types:
throw new TypeError('Must be a number!');
throw new RangeError('Value too large!');

Error types in Node.js (specific)

Node.js has its own system errors that occur when working with files, network, etc.:

Error Code Description
... ...
```