Error Handling (Japanese)

JavaScript error handling involves handling runtime errors and exceptions that occur during code execution.

To handle errors effectively, various techniques and mechanisms are available.

Below, we demonstrate error handling techniques and mechanisms in JavaScript that can make your code more robust and help you deal with exceptional situations.

Methods

  1. try-catch: The try block contains code that may throw an exception, and the catch block is where the exception can be caught and an exception handling code block executed. This allows handling errors without interrupting the code's execution.

  2. throw: Developers can directly throw exceptions using the throw keyword, allowing them to create exceptions for specific conditions or error situations.

  3. finally: Used in conjunction with try-catch statements, the finally block is executed regardless of whether an exception is thrown. It is mainly used for cleanup tasks and resource release.

  4. Error Object: JavaScript provides various built-in error objects, such as SyntaxError and TypeError, each indicating a specific error type. These error objects contain detailed information about the exception, aiding in debugging.


try-catch

The try block contains code that might throw an exception, and the catch block is where the exception can be handled.

In the example, the try block performs a division operation on variables x and y. If an exception occurs during the division, the catch block catches the exception and outputs an error message. This way, exceptions can be handled without interrupting the code's execution.

try-catch

try {
    // 예시: 예외를 발생시키는 코드
    const result = x / y; // x와 y를 나누는 연산에서 예외 발생 가능
} catch (error) {
    // 예시: 예외를 처리하는 코드
    console.error("오류가 발생했습니다: " + error.message);
}

throw

The throw statement is used for users to generate errors directly. By utilizing this, custom errors can be created, thrown, and then caught and handled using try-catch blocks.

In the example, the divide function takes two numerical arguments. If the second number is 0, it throws a custom error message: "Cannot divide by 0." Subsequently, this error is caught, and a try-catch block is used to output the error message. This allows the detection and handling of exceptional situations.

throw

function divide(a, b) {
    if (b === 0) {
        throw new Error("0으로 나누는 것은 허용되지 않습니다.");
    }
    return a / b;
}

try {
    let result = divide(10, 0);
    console.log(result);
} catch (error) {
    console.log("오류 발생:", error.message);
}

finally

The finally block is an optional block that follows the try-catch block. The code within the finally block is always executed, regardless of whether an exception is thrown.

It is primarily used for performing cleanup tasks and resource release, such as database connections. This ensures that essential termination procedures, like cleanup and resource deallocation, are executed regardless of whether an exception occurred or not.

finally

function divide(a, b) {
    try {
        if (b === 0) {
            throw new Error("0으로 나누는 것은 허용되지 않습니다.");
        }
        return a / b;
    } catch (error) {
        console.log("오류 발생:", error.message);
    } finally {
        console.log("마무리 작업을 수행합니다.");
    }
}

console.log(divide(10, 2)); // 정상적인 경우
console.log(divide(10, 0)); // 예외 발생한 경우

Error Object

JavaScript provides built-in error objects representing various types of errors. These objects offer different information about the errors. The main built-in error objects include Error, TypeError, SyntaxError, ReferenceError, RangeError, EvalError, URIError, and more. These error objects are valuable for exception handling and debugging purposes.

  • Name
    TypeError
    Type
    Description

    Error that occurs when an unexpected data type is used.

  • Name
    SyntaxError
    Type
    Description

    Error that occurs when there is a syntax error in the code. It occurs when invalid code is written.

  • Name
    ReferenceError
    Type
    Description

    Error that occurs when there is an invalid reference. It happens when accessing undeclared variables or non-existing objects.

  • Name
    RangeError
    Type
    Description

    Error that occurs when a number exceeds the permissible range. For example, errors related to array length.

  • Name
    EvalError
    Type
    Description

    Error that occurs during the execution of the eval() function.

  • Name
    URIError
    Type
    Description

    Error that occurs when an invalid URI operation is performed.