What is the main reason of using try catch?

Arcticooling asked
javascript try-catch
via

Please take a look at this JavaScript code example demonstrating try-catch code. Its purpose is to be a simple example to a try-catch code, to learn the concept.

let age = prompt(`Please enter your age, `));
let err1 = `Error: Make sure field isn't empty and only a number is given`;
let err2 = `Error: Age out of range`;

try (
    if (age == "" || isNaN(age)) {
        throw err1;
    } else if (age < 0 || age > 120) {
        throw err2;
    }
)

catch (error) {
    if (error == err1) {
        console.log('Age was either empty or non solely numerical.');
    } else if (error == err2) {
        console.log('A solely numerical age was given, but it was beyond range.');
    }
    exit;
}

From the example I can assume that the main reason for using try-catch codes is to better organize the code (especially, better organizing the outcome of each error), even though we could achieve its exact results without try and catch, and in a more imperative code (the outcome of each error would be defined in row for example, instead later in a catch block).

Is better organization of the code (especially, custom error handling) the main reason to combine these two blocks in our codes?


Answer
via

The main advantage of using a try{} catch(exception){} is that you’re able to shift control to the catch(exception){} in the event that an exception is thrown, which allows you to continue processing, as opposed to your script failing miserably. In short, you’re catching the exception.

In other words, the main reason is to catch an exception, and then decide what action you’d like to take. Is it possible that you can you approach the problem in a different way and complete the task without failing? If so, that’s where catch(exception){ // do something different } comes into play. In a manner of speaking, it offers you a second chance :-)

Share This
Posted in: