try...catch...finally . Errors catching in JavaScript. CodeE... open

try...catch...finally . Errors catching in JavaScript. CodeExamples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

During the program’s operation, various errors may occur that disrupt the usual course of the program and even force it to interrupt execution.

The simplest situation is calling a function that doesn’t exist:

    callSomeFunc();

    console.log("Next");

This calls the callSomeFunc() function, which is not defined anywhere. Accordingly, when calling this function, we will encounter an error:

Uncaught ReferenceError: callSomeFunc is not defined

All other instructions that come after the line on which the error occurred are not executed. The program ends its work.

To avoid such, we can apply the try…catch…finally construction:

    try {
        //This block contains instructions that may result in a potential error
    }
    catch (error) {
        //error - an object with information about the error
        //This block is executed only when an error occurs in the try block 
    }
    finally {
        //This block is executed at the end after the try and catch block, whether an error occurred or not.
    }
Only the try block is required. And we can omit one of the other blocks – catch or finally.

For example, let’s use this construction to process the previous situation with a non-existent function:

    try {
        callSomeFunc();
    }
    catch {
        console.log("An error has occurred!");
    }
    console.log("Other instructions");

An object with information about the error is passed as a parameter to the catch block:

    try {
        callSomeFunc();
    }
    catch (error) {
        console.log(error);//error info - ReferenceError: callSomeFunc is not defined
        //at index.html:13
    }
Throw in JavaScript. Code examples open
Throw in JavaScript. Code examples
September 6, 2022
Roman-tk
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation