EXCEPTION HANDLING IN C++
What is Exception Handling?
Definition: A way to manage errors during program execution.
Goal: Prevent the program from crashing and handle errors gracefully.
Why Use Exception Handling?
Avoid sudden crashes.
Manage errors without cluttering the code.
Handle unexpected situations (e.g., dividing by zero).
Basic Structure in C++
try: Code that might cause an error.
throw: Used to trigger an error.
catch: Code that handles the error.
#include <iostream>
#include <stdexcept>
int safeDivide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero is not allowed.");
}
return a / b;
}
int main() {
try {
int result = safeDivide(10, 0); // Change 0 to non-zero to avoid error
std::cout << "Result: " << result << std::endl;
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
Throwing an Exception
Use throw to create an error:
throw std::runtime_error("Something went wrong");
Catching Exceptions
Use catch to handle an error:
try {
// Code that might cause an error
}
catch (std::exception& e) {
std::cout << "Caught error: " << e.what() << std::endl;
}
Multiple Catches
try {
// Code that may throw different errors
}
catch (std::out_of_range& e) {
std::cout << "Out of range: " << e.what() << std::endl;
}
catch (std::invalid_argument& e) {
std::cout << "Invalid argument: " << e.what() << std::endl;
}
Re-Throwing Exceptions
Re-throw an exception:
catch (std::exception& e) {
std::cout << "Caught: " << e.what() << std::endl;
throw; // Rethrow the same exception
}
Best Practices
Use exceptions for unexpected errors.
Don’t use exceptions for normal control flow.
Catch exceptions by reference (catch (const std::exception& e)).
#include <iostream>
#include <stdexcept> // For std::invalid_argument
void checkAge(int age) {
if (age < 12 || age > 18) {
throw std::out_of_range("Age must be between 12 and 18.");
}
}
int main() {
int age;
std::cout << "Enter your age: ";
try {
std::cin >> age;
if (std::cin.fail()) {
throw std::invalid_argument("Invalid input. Please enter a number.");
}
checkAge(age);
std::cout << "Valid age: " << age << std::endl;
}
catch (const std::out_of_range& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
catch (const std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
Standard Exceptions
From <exception>:
•std::exception: Base class for all standard exceptions.
•std::bad_alloc: Thrown when new fails to allocate memory.
•std::bad_cast: Thrown during an invalid type cast using dynamic_cast.
•std::bad_typeid: Thrown when using typeid on a null pointer to a polymorphic type.
•std::bad_exception: Used with unexpected exception handling.
From <stdexcept>:
•std::logic_error: Errors in the program logic.
•std::invalid_argument: Invalid argument passed to a function.
•std::domain_error: Input domain error.
•std::length_error: Length exceeds maximum size.
•std::out_of_range: Accessing elements out of valid range.
•std::runtime_error: Errors detected during program execution.
•std::overflow_error: Arithmetic overflow.
•std::underflow_error: Arithmetic underflow.
•std::range_error: Result is out of the expected range.
Summary
try: Code that may throw an error.
throw: Used to create an error.
catch: Used to handle the error.
Exception handling helps make your program more stable and user-friendly.