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?