JavaScript
Challenge - Error handling
Write a function that validates age using try/catch and throw.
Age validation challenge
In this challenge you will write an age validation function. It takes an age parameter and returns true when valid, false otherwise.
The validation is wrapped in try/catch. The try block checks for negative age; if invalid it throws with throw new Error(...). The catch block catches the error and returns false.
This pattern combines throwing and catching. The Error object carries a message property; you can read it as e.message when needed.
The try/catch structure
The try block runs the risky code. If no error occurs, catch is skipped; if an error occurs, the catch (e) block runs and the e parameter carries the error.
You can deliberately throw with throw new Error("message"). This interrupts the normal flow and passes control to catch.
For age validation, a negative age is a validation error. You express it with throw and handle it gently by returning false in catch. This prevents the program from crashing.
Exercise Write the validateAge function
Define a function named validateAge. It should take an age parameter. Open a try block and inside it check for negative age with if (age < 0); when true, throw with throw new Error(...). At the end of try return true for a valid age. On error the catch (e) block should return false.
Show example solution
Inside validateAge open a try block. Check negative age with if (age < 0); throw new Error. Return true for valid ages. In the catch (e) block return false.
Example solution:
function validateAge(age) {
try {
if (age < 0) {
throw new Error("Negative age");
}
return true;
} catch (e) {
return false;
}
}
Test yourself
-
When does the catch block run?
try {
// risky code
} catch (e) {
// error handling
}
- When an error is thrown in the try block
- When the try block finishes cleanly
- When there is no finally block
- When return is called
Show answer
When an error is thrown in the try block — Correct. When an error is thrown in the try block, flow jumps to catch and the e parameter carries the error.
-
Throw an error for a too-large age
function validateAge(age) {
try {
if (age > 120) {
____;
}
return true;
} catch (e) {
return e.message;
}
}
Show answer
function validateAge(age) {
try {
if (age > 120) {
throw new Error("Too large");
}
return true;
} catch (e) {
return e.message;
}
}
Next lesson: Beginner section exam