Osi
Osi

Reputation: 1

What is the main reason of using try catch?

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?

Upvotes: 0

Views: 110

Answers (2)

jaswrks
jaswrks

Reputation: 1285

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 :-)

Upvotes: 1

Eumel
Eumel

Reputation: 1433

The main reason for try catch is to stop errors from crashing your programm. In this example if the user gives an age thats not a number and you try to process it later on in your code might crash or not work as intended.

Upvotes: 0

Related Questions