What is logic_error in C++: Explanation and Example
logic_error in C++ is a standard exception type used to signal errors in the program's logic, such as invalid arguments or broken assumptions. It is part of the std::exception family and helps catch mistakes that can be detected before the program runs incorrectly.How It Works
Imagine you are following a recipe to bake a cake. If you add salt instead of sugar, the cake won't taste right because the instructions were not followed correctly. In programming, logic_error is like a warning that the recipe (your program's logic) has a mistake.
When your program detects a situation that should never happen if the logic is correct, it can throw a logic_error. This exception tells the program to stop normal execution and handle the problem, preventing further errors or incorrect results.
It is part of C++'s standard library exceptions and is used to catch errors that come from wrong assumptions or invalid operations in the code, such as passing a wrong value to a function or violating a rule your program depends on.
Example
This example shows how to throw and catch a logic_error when a function receives an invalid argument.
#include <iostream> #include <stdexcept> void checkAge(int age) { if (age < 0 || age > 150) { throw std::logic_error("Age must be between 0 and 150."); } std::cout << "Age is valid: " << age << std::endl; } int main() { try { checkAge(25); // valid age checkAge(-5); // invalid age, will throw } catch (const std::logic_error& e) { std::cout << "Logic error caught: " << e.what() << std::endl; } return 0; }
When to Use
Use logic_error when your program detects a problem caused by incorrect logic or invalid input that breaks your program's rules. For example:
- Checking function arguments for invalid values.
- Detecting impossible states in your program.
- Signaling that a precondition or assumption was violated.
This helps you find bugs early and handle them gracefully instead of letting the program continue with wrong data.
Key Points
logic_erroris a standard exception for logic mistakes in code.- It inherits from
std::exceptionand can be caught using standard exception handling. - Throw it when your program detects invalid arguments or broken assumptions.
- Helps improve program reliability by catching bugs early.
Key Takeaways
logic_error signals errors caused by incorrect program logic or invalid input.std::exception.logic_error to catch broken assumptions or invalid arguments.logic_error helps prevent bugs and unexpected behavior.