Handling std::domain_error in C++

2025-09-18

One of the most common issues with std::domain_error is that it's often thrown when you don't expect it, leading to a program crash if it's not handled properly. Here are some scenarios where it often pops up

Mathematical functions
Functions like std::sqrt() will throw a std::domain_error if you pass a negative number to it, as the square root of a negative number is not defined in the real number domain. Similarly, std::log() will throw this error if you try to take the logarithm of a non-positive number (zero or a negative number).

Custom functions
You might write your own function that has a specific valid range for its input. For instance, a function that calculates the factorial of a number might only be designed to work with non-negative integers. If a user passes a negative number, std::domain_error is a great way to let them know something's wrong.

Failure to validate input
If you're getting user input, you should always validate it before using it in calculations. If a user enters a negative number for a calculation that requires a positive one, and you don't check for it, you're setting yourself up for an exception.

Instead of just letting a std::domain_error crash your program, you can handle it gracefully. The two most common ways to deal with this are using a try-catch block or validating the input before the function call.

The try-catch block is the standard C++ way to handle exceptions. You "try" to run the code that might throw an exception, and if it does, you "catch" it and handle the error. This is useful when you're not sure if the input will be valid.

#include <iostream>
#include <cmath>
#include <stdexcept>

int main() {
    double x;
    std::cout << "Enter a number to find its square root: ";
    std::cin >> x;

    try {
        if (x < 0) {
            throw std::domain_error("Cannot take the square root of a negative number!");
        }
        double result = std::sqrt(x);
        std::cout << "The square root is: " << result << std::endl;
    } catch (const std::domain_error& e) {
        std::cerr << "Caught an exception: " << e.what() << std::endl;
    }

    return 0;
}

In this example, we explicitly throw a std::domain_error if the input is negative. The catch block then handles it by printing a helpful message to the user, preventing the program from crashing.

A more proactive approach is to check the input before you even call the function. This can often be cleaner and more efficient than using a try-catch block, especially if the invalid inputs are common.

#include <iostream>
#include <cmath>

int main() {
    double x;
    std::cout << "Enter a number to find its square root: ";
    std::cin >> x;

    if (x >= 0) {
        double result = std::sqrt(x);
        std::cout << "The square root is: " << result << std::endl;
    } else {
        std::cerr << "Error: The number must be non-negative." << std::endl;
    }

    return 0;
}

In this code, we use a simple if statement to ensure the number is valid before we even call std::sqrt(). This prevents the exception from ever being thrown, making your code safer and often easier to read. For many situations, this is the preferred method.


cpp



Avoiding Errors with C++ std::match_results::operator[]

One of the most frequent problems is trying to access a submatch that doesn't exist. This happens when you use an index that's greater than or equal to the number of submatches found


Best Practices for C++'s extreme_value_distribution

The extreme_value_distribution has two parameters a (the location parameter) and b (the scale parameter).a This shifts the distribution along the x-axis


C++ I/O: Understanding std::basic_streambuf::showmanyc()

I'll break down the common issues and offer alternative approaches with code examples.First, let's quickly explain what showmanyc() does



Troubleshooting and Alternatives for std::chrono::month Formatting in C++

First, let's quickly recap what std::formatter<std::chrono::month> is all about. It's part of the C++20 <chrono> and <format> libraries


Mastering C++ std::distance: Common Pitfalls and Alternatives

The std::distance function in C++ is a great tool for calculating the number of elements between two iterators. It's often used to determine the size of a sub-range or to get an index


Common Issues and Alternatives for C++'s notify_one

The main purpose of std::condition_variable::notify_one is to wake up a single thread that's waiting on a condition variable


Troubleshooting consteval in C++: Common Errors and Solutions

consteval is a C++ keyword that appeared in C++20. It's used to force a function to be evaluated at compile time. This is different from constexpr


Troubleshooting std::uses_allocator in C++

Hey there! Let's talk about some of the common pitfalls you might encounter when using std::uses_allocator<std::promise> in C++. This template is a bit of a niche feature


Modern C++ Alternatives: std::chrono

Let's dive into some of the most common issues and then look at modern, safer alternatives.std::tm is a simple struct that holds the components of a calendar date and time year


A Practical Guide to C++'s std::bit_xor

The std::bit_xor<void> is a function object in C++ that performs a bitwise XOR operation. It's a handy tool for generic programming