0

I am trying to catch pointer exception. My code looks like this. I am getting "Unhandled exception". What is it that I am doing wrong? Any help will be appreciated.

 #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;
}
andrey
  • 1,867
  • 3
  • 21
  • 34

1 Answers1

5

There is no C++ exception here. You just dereference null pointer, that is undefined behaviour, not exception. You should just check, that head is not nullptr before dereference it. Probably, you are using windows and windows exception is thrown. You can read here: How to catch the null pointer exception?

Community
  • 1
  • 1
ForEveR
  • 55,233
  • 2
  • 119
  • 133