The 'throw' Keyword
Part of the Logic & Flow section of Coddy's C++ journey — lesson 50 of 56.
Sometimes you need to signal that an error has occurred in your own code, rather than just catching exceptions thrown by other functions. The throw keyword allows you to manually trigger an exception when your program detects a problem.
You can throw different types of values as exceptions - integers, strings, or even custom objects. Here's the basic syntax:
if (someErrorCondition) {
throw "Error message"; // Throws a string literal
}When you use throw, the program immediately stops executing the current function and looks for a catch block that can handle the thrown value. This is particularly useful for validating input or checking conditions that shouldn't occur during normal program execution.
Here's a practical example of throwing an exception when detecting invalid input:
void checkAge(int age) {
if (age < 0) {
throw "Age cannot be negative!";
}
std::cout << "Age is valid: " << age << std::endl;
}The throw keyword gives you control over when and how errors are reported in your programs, making your functions more robust and predictable when dealing with invalid conditions.
Challenge
EasyCreate a program that implements input validation using the throw keyword to manually trigger exceptions when invalid conditions are detected. This challenge will test your understanding of how to use throw to signal errors in your own functions.
The following inputs will be provided:
- A string
usernamerepresenting a user's chosen username - An integer
agerepresenting the user's age
Your program should:
- Create a function named
validateUserthat takes a string and an integer as parameters - Inside the function, check if the username is empty (has length 0)
- If the username is empty,
throwthe string"Username cannot be empty" - Check if the age is less than 13
- If the age is less than 13,
throwthe string"Age must be at least 13" - If both validations pass, print
"User validation successful" - In the main function, call
validateUserwith the input values - Use a
tryblock to call the function and acatchblock to handle any thrown string exceptions
Use the following exact output format:
For successful validation:
User validation successfulFor validation errors:
Validation error: [error_message]Remember that when you use throw, the program immediately stops executing the current function and looks for a matching catch block. The catch block should specify the type const char* to handle the thrown string literals. If the first validation fails, the function will throw an exception and not continue to check the second condition.
Cheat sheet
The throw keyword allows you to manually trigger exceptions when your program detects a problem:
if (someErrorCondition) {
throw "Error message"; // Throws a string literal
}When you use throw, the program immediately stops executing the current function and looks for a catch block that can handle the thrown value.
Example of throwing an exception for input validation:
void checkAge(int age) {
if (age < 0) {
throw "Age cannot be negative!";
}
std::cout << "Age is valid: " << age << std::endl;
}You can throw different types of values as exceptions - integers, strings, or custom objects. Use const char* in catch blocks to handle thrown string literals.
Try it yourself
#include <iostream>
#include <string>
using namespace std;
int main() {
// Read input
string username;
int age;
cin >> username;
cin >> age;
// TODO: Write your code here
// Create the validateUser function and implement the validation logic
// Use try-catch blocks to handle exceptions
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items8Basic Error Handling
Introduction to ExceptionsThe 'try' and 'catch' BlocksThe 'throw' KeywordDifferent Exception TypesThe Catch-All HandlerRecap - Safe Division