C/C++

Крашится программа после throw *char

#include <iostream>
using namespace std;

//exceptions catch of diferent types
void xhandler(int test)
{
try {
if(test) throw test;
else throw "value is null";
}
catch(int i){
cout << "catching! exception number: " << i << "\n";

}
catch(char *str) {
cout << "catching string: ";
cout << str << '\n';
}
}

int main()
{
cout << "START\n";

xhandler(1);
xhandler(2);
xhandler(0);
xhandler(3);

cout << "The end";

return 0;


}


после выполнения проги пишет:
terminate called after throwing an instance of 'char const* '

код из книги, может какая-то опечатка...
#include <iostream>
using namespace std;

//exceptions catch of diferent types
void xhandler(int test)
{
char t[] = "value is null";
try {
if(test) throw test;
else throw t;
}
catch(int i) {
cout << "catching! exception number: " << i << "\n";

}
catch(char *str) {
cout << "catching string: ";
cout << str << '\n';
}
}

int main()
{
cout << "START\n";

xhandler(1);
xhandler(2);
xhandler(0);
xhandler(3);

cout << "The end";

return 0;

}
Ринат Серодеев
Ринат Серодеев
67 112
Лучший ответ
#include <iostream>
#include <string>
using namespace std;
pair<bool, int> integer_type(const char* msg = ">>> ") {
int value;
string tmp;
auto status = true;
try {
cout << msg;
cin >> tmp;
value = stoi(tmp);
} catch (const invalid_argument& ex) {
cerr << ex.what() << '\n';
status = false;
value = 0;
} catch (const overflow_error& ex) {
cerr << ex.what() << '\n';
status = false;
value = 0;
} catch (...) {
cerr << "Unknown exception!\n";
status = false;
value = 0;
}
if (!status) cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return { status, value };
}
int main() {
auto [status, value] = integer_type("Integer: ");
try {
if (!status) throw exception("Warning: base_type function returned default value");
} catch (const exception& ex) {
cerr << ex.what() << '\n';
}
system("pause > nul");
}
Slava Fedina
Slava Fedina
58 082
catch(const char *str) {
cout << "catching string: ";
cout << str << '\n';
}

char *str и const char *str все-таки разные вещи ;)
да и вообще почему string не использовать
Евгений Владимирович хах, читаю книгу 2008 года