在Linux环境下,C++异常处理主要依赖于C++标准库中的<exception>
头文件提供的功能。以下是一些基本的C++异常处理方法:
throw
关键字抛出一个异常对象。例如:#include <iostream> #include <stdexcept> int main() { if (some_error_condition) { throw std::runtime_error("An error occurred"); } return 0; }
try
和catch
块来捕获和处理异常。例如:#include <iostream> #include <stdexcept> int main() { try { // Code that might throw an exception if (some_error_condition) { throw std::runtime_error("An error occurred"); } } catch (const std::runtime_error& e) { // Handle the exception std::cerr << "Caught exception: " << e.what() << std::endl; } return 0; }
catch
块来捕获和处理不同类型的异常。例如:#include <iostream> #include <stdexcept> int main() { try { // Code that might throw an exception if (some_error_condition) { throw std::runtime_error("An error occurred"); } } catch (const std::runtime_error& e) { // Handle the runtime_error exception std::cerr << "Caught runtime_error: " << e.what() << std::endl; } catch (const std::exception& e) { // Handle any other standard exceptions std::cerr << "Caught exception: " << e.what() << std::endl; } catch (...) { // Handle any other exceptions std::cerr << "Caught an unknown exception" << std::endl; } return 0; }
std::exception
或其派生类,并重写what()
方法以提供自定义的错误信息。例如:#include <iostream> #include <stdexcept> class MyCustomException : public std::runtime_error { public: MyCustomException(const std::string& message) : std::runtime_error(message) {} }; int main() { try { // Code that might throw an exception if (some_error_condition) { throw MyCustomException("A custom error occurred"); } } catch (const MyCustomException& e) { // Handle the custom exception std::cerr << "Caught custom exception: " << e.what() << std::endl; } catch (const std::runtime_error& e) { // Handle the runtime_error exception std::cerr << "Caught runtime_error: " << e.what() << std::endl; } catch (const std::exception& e) { // Handle any other standard exceptions std::cerr << "Caught exception: " << e.what() << std::endl; } catch (...) { // Handle any other exceptions std::cerr << "Caught an unknown exception" << std::endl; } return 0; }
这些是C++异常处理的基本概念。在实际编程中,应根据具体需求选择合适的异常处理方法。