本文收集了有关C++异常的常用实例,附精简代码。
关键词:C++异常 C++ Exception try/catch throw
- 异常捕获:使用try/catch捕获异常。
#include <iostream>
#include <string>
#include <stdexcept>
int main() {
std::string str("foo");
try {
str.at(10); // access element, may throw std::out_of_range
} catch (const std::out_of_range& e) {
// what() is inherited from std::exception and contains an explanatory message
std::cout << e.what();
}
}
- 连续多个异常捕获
std::string str("foo");
try {
str.reserve(2); // reserve extra capacity, may throw std::length_error
str.at(10); // access element, may throw std::out_of_range
} catch (const std::length_error& e) {
std::cout << e.what();
} catch (const std::out_of_range& e) {
std::cout << e.what();
} catch (const std::exception& e) {
std::cout << e.what();
}
- 捕获任意异常/捕获所有异常,或者叫匿名捕获异常
try {
throw 10;
} catch (...) {
std::cout << "caught an exception";
}
- 异常捕获最佳实践:抛出异常值,捕获异常值的引用,可以避免不必要的开销。
try {
// throw new std::runtime_error("Error!");
// Don't do this!
// This creates an exception object
// on the heap and would require you to catch the
// pointer and manage the memory yourself. This can
// cause memory leaks! throw std::runtime_error("Error!");
} catch (const std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
- 将异常简单处理之后,继续抛出
try {
... // some code here
} catch (const SomeException& e) {
std::cout << "caught an exception";
throw;
}
- 自定义C++异常
#include <exception>
class Except: virtual public std::exception {
protected:
int error_number; ///< Error number
int error_offset; ///< Error offset
std::string error_message; ///< Error message
public:
/** Constructor (C++ STL string, int, int).
* @param msg The error message
* @param err_num Error number
* @param err_off Error offset
*/
explicit Except(const std::string& msg, int err_num, int err_off):
error_number(err_num), error_offset(err_off),error_message(msg) {}
/** Destructor.
* Virtual to allow for subclassing.
*/
virtual ~Except() throw () {}
/** Returns a pointer to the (constant) error description.
* @return A pointer to a const char*. The underlying memory
* is in possession of the Except object. Callers must
* not attempt to free the memory.
*/
virtual const char* what() const throw () {
return error_message.c_str();
}
/** Returns error number.
* @return #error_number
*/
virtual int getErrorNumber() const throw() { return error_number; }
/**Returns error offset.
* @return #error_offset
*/
virtual int getErrorOffset() const throw() { return error_offset; }
};
- 抛出上述自定义异常
try {
throw(Except("Couldn't do what you were expecting", -12, -34));
} catch (const Except& e) {
std::cout<<e.what() <<"
Error number: "<<e.getErrorNumber() <<"
Error offset: "<<e.getErrorOffset();
}