Account
Categories

Try and Catch


Definition:

When you write a program, and you use the try and catch method,
you write the code that may produce an error inside the try block,
and the message that explains the error is placed inside the catch block.
And when you run the program, the try block checks for the error.
If it finds the error, the catch block runs the code and displays the message,
and if it does not find the error, then the try block runs the code.
You can use this method in functions, switch statements, if-else blocks, etc.

Now you will clearly understand the code logic with the help of the flowchart.

Start
  |
  v
Write code inside Try block
  |
  v
Run Try block
  |
  v
Is there an error?
  |
  |--- Yes ---> Run Catch block ---> Display "error" ---> End
  |
  |--- No ----> Try block completes ---> End
  

Syntax:

try {
    // Code that may cause an error
} catch(error) {
    // Code to handle the error
}

Example:

try {
    let result = 5 / 0;
    if (!isFinite(result)) {
        throw "Division by zero is not allowed";
    }
}
catch (error) {
    console.log("error");
}

Output:

error