【问题标题】:C++ how to catch an exception? [duplicate]C++如何捕捉异常? [复制]
【发布时间】:2015-12-19 04:12:01
【问题描述】:

我正在尝试捕获指针异常。我的代码看起来像这样。我收到“未处理的异常”。我做错了什么? 任何帮助将不胜感激。

 #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++ exception-handling


    【解决方案1】:

    这里没有 C++ 异常。您只是取消引用空指针,这是未定义的行为,而不是异常。您应该在取消引用之前检查 head 不是 nullptr 。可能,您正在使用 windows 并且会引发 windows 异常。你可以在这里阅读:How to catch the null pointer exception?

    【讨论】:

    • 是的,我使用的是 Windows。现在我明白了,谢谢。
    猜你喜欢
    • 2013-03-29
    • 2010-12-21
    • 2012-03-20
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 2012-01-10
    • 2019-11-06
    • 2021-10-17
    相关资源
    最近更新 更多