Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create 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 username representing a user's chosen username
  • An integer age representing the user's age

Your program should:

  1. Create a function named validateUser that takes a string and an integer as parameters
  2. Inside the function, check if the username is empty (has length 0)
  3. If the username is empty, throw the string "Username cannot be empty"
  4. Check if the age is less than 13
  5. If the age is less than 13, throw the string "Age must be at least 13"
  6. If both validations pass, print "User validation successful"
  7. In the main function, call validateUser with the input values
  8. Use a try block to call the function and a catch block to handle any thrown string exceptions

Use the following exact output format:

For successful validation:

User validation successful

For 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;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow