c++如何捕获异常

C++ how to catch an exception?

本文关键字:捕获异常 c++      更新时间:2023-10-16

我正在尝试捕获指针异常。我的代码是这样的。我得到"未处理的异常"。我到底做错了什么?如有任何帮助,不胜感激。

 #include <iostream>
 #include <exception>
using namespace std;
struct Node{
    int data;
    Node* next;
};
int list_length(struct Node* head){
    try{
        int i = 0;
        while (head->next){
            head = head->next;
            i++;
        }
        return i + 1;
    }
    catch (exception& e){
        cout << e.what() << endl;
    }
};
int main(void){
    struct Node *perr = nullptr;
    list_length(perr);
    return 0;
}

这里没有c++的例外。你只是解引用空指针,那是未定义的行为,不是异常。在解引用之前,你应该检查一下,head不是nullptr。可能,您正在使用窗口,并且抛出了窗口异常。你可以在这里阅读:如何捕捉空指针异常?