Codecademy Logo

Error Handling in C++

Related learning

  • Learn advanced C++ programming with preprocessor directives, operator overloading, streams, and lambda expressions.
    • With Certificate
    • Advanced.
      9 hours

C++ Exception Handling

In C++, constructors should not throw exceptions to maintain program stability. If unavoidable, use a try-catch block around the constructor call. Destructors, however, should never throw exceptions, as they may lead to termination if invoked during stack unwinding.

#include <iostream>
#include <exception>
class Resource {
public:
Resource() {
try {
// Code that may throw an exception
throw std::runtime_error("Error initializing resource");
} catch (const std::exception& e) {
std::cerr << "Exception in constructor: " << e.what() << std::endl;
}
}
~Resource() noexcept {
std::cout << "Destructor called, ensuring no exception thrown." << std::endl;
// Code to clean up resources
// Never throw exceptions from the destructor
}
};
int main() {
Resource resource;
return 0;
}

C++ Exceptions

In C++, exceptions serve as a structured mechanism for error handling. They are objects that represent errors or unexpected behaviors during program execution. This allows developers to manage errors effectively, separating normal execution flow from error management.

C++ Try Blocks

In C++, try blocks help capture exceptions that may occur during execution, allowing for cleaner error management. They are complemented by catch blocks, where specific actions are defined for handling the exceptions.

try {
// Code that might throw an exception
int divisor = 0;
int result = 100 / divisor;
} catch (std::exception& e) {
std::cerr << "Exception occurred: " << e.what() << std::endl;
}

C++ Catch Blocks

In C++, catch blocks handle exceptions that arise in a try block. You can specify multiple catch blocks for various exception types to manage errors precisely. This enables your program to react differently based on the kind of exception it encounters, keeping your application robust.

try {
// Code that may throw an exception
throw 1;
} catch (int e) {
std::cout << "Caught an integer exception: " << e << std::endl;
} catch (std::exception& e) {
std::cout << "Caught a standard exception: " << e.what() << std::endl;
}

C++ throw Keyword

In C++, use the throw keyword to signal an exceptional circumstance, such as an error. This keyword transfers control to a matching catch block, where the error can be managed. Remember, encapsulating error-prone code with try and catch ensures robust error handling.

#include <iostream>
#include <stdexcept>
void divide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero not allowed.");
}
std::cout << "Result: " << a / b << std::endl;
}
int main() {
try {
divide(10, 0);
} catch (const std::runtime_error& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
}

C++ noexcept Keyword

The C++ noexcept specifier prevents a function from throwing exceptions and allows for compiler optimizations. It serves to inform users of the function about the absence of exceptions, potentially increasing trust in the function’s stability and performance.

#include <iostream>
// Function declared with noexcept
void exampleFunction() noexcept {
std::cout << "This function won't throw exceptions." << std::endl;
}
int main() {
exampleFunction();
return 0;
}

C++ Exception Rethrowing

In C++, you can rethrow an exception from within a catch block to allow it to be handled by a surrounding try-catch structure. This is done using the throw; statement, which propagates the exception up the call stack.

#include <iostream>
void innerFunction() {
try {
throw std::runtime_error("Inner function exception");
} catch (const std::runtime_error &e) {
std::cout << "Caught in inner: " << e.what();
throw; // Rethrowing the exception
}
}
int main() {
try {
innerFunction();
} catch (const std::runtime_error &e) {
std::cout << "Caught in outer: " << e.what();
}
return 0;
}

C++ Custom Exceptions

In C++, you can create custom exception classes by inheriting from existing standard exception classes. This allows you to provide specific error information while adhering to a structured exception hierarchy.

#include <iostream>
#include <stdexcept>
class CustomException : public std::runtime_error {
public:
explicit CustomException(const std::string& message)
: std::runtime_error(message) {}
};
int main() {
try {
throw CustomException("Custom error occurred!");
} catch (const CustomException& e) {
std::cerr << "Caught a custom exception: " << e.what() << std::endl;
}
return 0;
}

Learn more on Codecademy

  • Learn advanced C++ programming with preprocessor directives, operator overloading, streams, and lambda expressions.
    • With Certificate
    • Advanced.
      9 hours