Here we have a practical example that uses try, throw, and catch in an age verification system, essential for many web applications dealing with age-restricted content. We can imagine a scenario where a user must be at least 18 years old to access a certain feature or product.
We place the code that might throw an exception (in this case the user being underage) inside a try
block, and we handle the exception in the catch
block. If an exception is thrown (i.e., the user's age is less than 18), the catch
block catches the exception and executes the code inside it.
Our code throws an exception if the age is less than 18. We then catch the exception and print a custom error message, notifying the user that they must be at least 18 to access the desired feature. We also print out the user's actual age by catching the thrown variable age
as myNum
.
This is a simplified example. In a real-world application, you would likely be working with more complex data and have more sophisticated error handling mechanisms. But it shows how try, throw, catch can be used as part of the error handling strategy in a web development context.
xxxxxxxxxx
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old." << '\n';
cout << "You are " << myNum << " years old.";
}
return 0;
}