How do I throw a C++ exception in a function?

I’m learning exception handling in C++ and want to understand how to use c++ throw exception properly. For example, I have a function:

int compare(int a, int b) { ... }

I want the function to throw an exception with a message when either a or b is negative. How should I implement throw, try, and catch in this scenario?

Hey! I’ve been there :sweat_smile:. In C++, you can use the throw keyword to signal an error, and catch it elsewhere with try/catch. Here’s a simple example for your compare function:

#include <iostream>
#include <stdexcept>  // for std::invalid_argument

int compare(int a, int b) {
    if (a < 0 || b < 0) {
        throw std::invalid_argument("Both numbers must be non-negative!");
    }
    return (a > b) ? a : b;
}

int main() {
    try {
        int result = compare(-5, 10);
        std::cout << "Result: " << result << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }

    return 0;
}

throw signals the exception.

std::invalid_argument is a standard C++ exception class for invalid input.

catch handles it so your program doesn’t crash.

Sometimes I like defining my own exception types for clarity:

#include <iostream>
#include <exception>

class NegativeNumberException : public std::exception {
public:
    const char* what() const noexcept override {
        return "Negative numbers are not allowed!";
    }
};

int compare(int a, int b) {
    if (a < 0 || b < 0) throw NegativeNumberException();
    return (a > b) ? a : b;
}

int main() {
    try {
        int result = compare(-2, 3);
    } catch (const NegativeNumberException& e) {
        std::cout << "Caught exception: " << e.what() << std::endl;
    }
}

Custom exceptions make your error handling more descriptive.

I often do this in larger projects to differentiate types of errors.

In real-world code, you might need to catch multiple exception types:


try {
    int result = compare(-1, -1);
} catch (const NegativeNumberException& e) {
    std::cout << "Negative number: " << e.what() << std::endl;
} catch (const std::exception& e) {
    std::cout << "Other exception: " << e.what() << std::endl;
}

The most specific exceptions first, general ones later.

I use this pattern when functions can throw multiple types of exceptions.