C++ Exception Handling Example: Throw and Catch Age Validation
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
This code provides a simple example of exception handling in C++. Inside the try block, an age variable is set to 15, and a condition checks if the age is greater than 18. If true, an access granted message is printed; otherwise, an exception is thrown.
The catch block catches the exception and displays an access denied message along with the age. This pattern is useful for error management in real-world applications.
- Using throw to raise an exception
- Using catch to handle exceptions
- Displaying appropriate messages based on conditions
To run, compile the code with a C++ compiler. The output will be 'Access denied' and 'Age is: 15'.