锦通 发表于 2024-8-13 12:20:39

c++的非常处理机制(try、catch、throw)

在C++中,非常处理机制通过try、catch和throw来管理程序运行时的错误环境。非常处理机制使得程序可以大概在出现错误时优雅地恢复或处理错误,而不是让程序崩溃。以下是关于C++非常处理的详细解说
1. throw 关键字

throw用于抛出非常。非常是一个表示错误或非常环境的对象。今世码中出现问题时,可以使用throw来创建一个非常对象并将其抛出。
示例:
#include <iostream>
#include <stdexcept> // std::runtime_error

void mightGoWrong() {
    bool errorOccurred = true; // 假设发生了错误
    if (errorOccurred) {
      throw std::runtime_error("Something went wrong");
    }
}

int main() {
    try {
      mightGoWrong();
    } catch (const std::exception& e) {
      std::cout << "Caught an exception: " << e.what() << std::endl;
    }
    return 0;
}
2. try 关键字

try块用于包含可能会抛出非常的代码。如果try块中的代码抛出了非常,那么控制流将转移到相应的catch块来处理该非常。
示例:
#include <iostream>

void mightGoWrong() {
    throw std::runtime_error("An error occurred");
}

int main() {
    try {
      mightGoWrong(); // 可能抛出异常
    } catch (const std::exception& e) {
      std::cout << "Caught exception: " << e.what() << std::endl;
    }
    return 0;
}
3. catch 关键字

catch用于捕获try块中抛出的非常。catch块指定了要捕获的非常范例,并处理该非常。可以定义多个catch块来捕获差别范例的非常。
示例:
#include <iostream>
#include <stdexcept>

void mightGoWrong() {
    throw std::runtime_error("Runtime error occurred");
}

int main() {
    try {
      mightGoWrong();
    } catch (const std::runtime_error& e) {
      std::cout << "Caught runtime_error: " << e.what() << std::endl;
    } catch (const std::exception& e) {
      std::cout << "Caught exception: " << e.what() << std::endl;
    }
    return 0;
}
非常处理机制的工作流程


[*] 抛出非常: 当throw语句被执行时,程序会创建一个非常对象并将其抛出。控制流将立即转移到try块外的catch块中。
[*] 捕获非常: catch块负责捕获和处理非常。它根据非常的范例和参数,决定怎样处理非常。catch块可以捕获详细范例的非常,也可以捕获基类非常(如std::exception)。
[*] 非常流传: 如果try块中抛出的非常没有被相应的catch块捕获,非常会沿着调用栈向上流传,直到找到匹配的catch块为止。如果在栈的顶端仍然没有捕获到该非常,程序将终止。
自定义非常

可以创建自定义非常类,继承自标准非常类(如std::exception)或其他非常类。
示例:
#include <iostream>
#include <exception>

class MyException : public std::exception {
public:
    const char* what() const noexcept override {
      return "MyException occurred";
    }
};

void mightGoWrong() {
    throw MyException();
}

int main() {
    try {
      mightGoWrong();
    } catch (const MyException& e) {
      std::cout << "Caught MyException: " << e.what() << std::endl;
    } catch (const std::exception& e) {
      std::cout << "Caught exception: " << e.what() << std::endl;
    }
    return 0;
}

非常安全



[*] 基本保证: 程序在非常发生时,能保证程序状态的一致性。
[*] 强保证: 在非常发生时,程序的状态与没有非常时完全相同。
[*] 无非常保证: 函数在任何环境下都不会抛出非常。
在C++中,非常处理机制使得程序可以更优雅地处理运行时错误,通过适当的try、catch和throw使用,可以进步程序的结实性和容错能力。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: c++的非常处理机制(try、catch、throw)