Home > Mobile >  C try/catch exceptions
C try/catch exceptions

Time:12-12

try {
    string message = "Error!";
    throw message;
}

Catch site.

catch (string* &e) {
court << e << endl;
    return 0;
}

Does anyone know how to fix this?

I want to display an error message but am required to do so with a C-string.

CodePudding user response:

You are not throwing the string or the array. Because of array-to-pointer decay you are throwing a pointer to the first element of the message array. You are catching that pointer just fine. Unfortunately during stack unwinding the array into which the pointer is pointing is destroyed since it is a local variable in the if block and your catch block is outside that if block. So you are then trying to dereference a dangling pointer in cout << *e << endl;, causing undefined behavior.

In theory you can do

const char* message = "Error! Invalid data for: Total Crew.";
throw message;

or

throw "Error! Invalid data for: Total Crew.";

to throw pointers to the string literals, which live until the end of the program, but that is really bad practice. You should instead write a class inherited from std::exception or another standard library exception class like std::invalid_argument and then throw an instance of your exception class. This way you can make catch clauses to handle specific types of exceptions, not just generic char* that could mean anything.


Also cout << *e << endl; would print only the first character of the string, even if there wasn't the lifetime issue. You probably meant cout << e << endl; instead.


but am required to do so with a C-string.

There is no good reason for that, except as far as all string literals are C-style strings. The exception classes inherited from std::exception allow one to provide a string argument to store in the exception object via the constructor and to retrieve it with the .what() member function in the catch handler.

You could even use them directly, without inheriting your own exception class:

if (totalCrew <=0) {
    throw std::invalid_argument("Error! Invalid data for: Total Crew.");
}

//...

catch (const std::invalid_argument& e) {
    cout << e.what() << endl;
    cout << "Line: " << line << endl;
    return 0;
}
  • Related