The C++ standard library
In C++ programming, exception handling is an important error-handling mechanism that allows a program to gracefully handle errors when they occur, rather than crashing.
In C++, exception handling is usually implemented using the try, catch, and throw keywords. The standard library provides the std::exception class and its derived classes to handle exceptions.
The C++ standard library's The header provides a set of exception-handling infrastructure, including exception classes and exception-handling mechanisms.
An exception is an event that occurs at runtime and interrupts the normal instruction flow. In C++, an exception can be an object of any type, but is usually an object of an exception class. The C++ standard library defines some basic exception classes, such as std::exception, std::bad_alloc, std::bad_cast , etc.
You can extend exception-handling functionality by defining your own exception classes, or use existing exception classes in the standard library to handle common exceptional situations.
Syntax
Throwing an Exception
In C++, use the throw keyword to throw an exception, with the following syntax:
throw exception_object;
Catching an Exception
Use the try and catch keywords to catch and handle exceptions, with the following syntax:
try {
// Code that might throw an exception
} catch (exception_type e) {
// Exception handling code
}
You can specify the exception type to catch, or use a generic catch block to catch all types of exceptions:
try {
// Code that might throw an exception
} catch (const std::exception& e) {
// Handle std::exception and its derived classes
} catch (...) {
// Handle all other types of exceptions
}
std::exception
std::exception is the base class defined in the C++ standard library, serving as the foundation for all standard exception classes. It defines some virtual functions, such as what(), used to return a C-style string of the exception message.
class exception {
public:
virtual const char* what() const noexcept;
};
Standard exception classes
The C++ standard library provides several exception classes derived from std::exception, such as std::runtime_error and std::logic_error, to represent common exceptional situations. You can choose the appropriate class based on the specific situation.
throw std::runtime_error("Runtime error occurred");
throw std::logic_error("Logic error occurred");
Example
Below is an example using header's simple example, demonstrating how to throw and catch exceptions.
Example
#include
#include
class
MyException
:
public
std
::
exception
{
public
:
const
char
what
(
)
const
throw
(
)
{
return
"My custom exception"
;
}
}
;
int
main
(
)
{
try
{
// Simulate an error condition
bool
error_condition
=
true
;
if
(
error_condition
)
{
throw
MyException
(
)
;
}
}
catch
(
const
std
::
exception
&
e
)
{
std
::
cout
<<
"Caught an exception: "
<<
e.
what
(
)
<<
std
::
endl
;
}
return
0
;
}
Output result:
Caught an exception: My custom exception
Exception classes
In C++, the standard library provides some commonly used exception classes; they all inherit from std::exception, and can be introduced via #include for use.
Here are some common C++ exception classes and their main purposes:
-
std::exception: The base class of all standard exception classes; defines the basic interface of exceptions. It has a virtual function
what(), used to return a C-style string of the exception message. -
std::runtime_error: Represents a runtime error, usually an exception caused by program logic issues, such as invalid arguments, failure to open a file, etc.
throw std::runtime_error("Runtime error occurred"); -
std::logic_error: Represents a logic error, usually an exception caused by program logic errors, such as failed logic assertions, out-of-bounds indices, etc.
throw std::logic_error("Logic error occurred"); -
std::invalid_argument: Represents an invalid argument passed to a function.
throw std::invalid_argument("Invalid argument"); -
std::out_of_range: Represents access to an object beyond its valid range, such as an array or container.
throw std::out_of_range("Out of range");
std::overflow_error and std::underflow_error: Represents overflow or underflow during numeric computation.
throw std::overflow_error("Overflow occurred");
throw std::underflow_error("Underflow occurred");
-
std::bad_alloc: Represents a memory allocation failure.
throw std::bad_alloc(); // 内存分配失败时抛出
Example
#include
#include
int
main
(
)
{
try
{
// Try to allocate a large amount of memory
int
largeArray
=
new
int
[
1000000000000
]
;
// Simulate a memory allocation failure
}
catch
(
const
std
::
bad_alloc
&
e
)
{
// Catch the std::bad_alloc exception and output the error message
std
::
cerr
<<
"Memory allocation failed: "
<<
e.
what
(
)
<<
std
::
endl
;
}
return
0
;
}
Output:
Memory allocation failed: std::bad_alloc
Notes
- Exceptions should not be used for normal control flow; they should only be used to handle exceptional situations.
- Exception handling may affect program performance, so it should be used with caution.
- Ensure that
catchblock handles all possible exception types, to avoid the program crashing on an unhandled exception.
By using header, C++ programmers can handle error conditions in programs more effectively, improving robustness and reliability.