exception handling problem

P

__PPS__

use stdexcept:

#include <stdexcept>
throw std::invalid_argument("Invalid command");

and

...
}catch(const std::exception& e){
cout << e.what() << endl;
}
 
A

Andre Kostur

Juhan Voolaid said:
Hi

I have function:

control_input(string input){
if(input!="open"){
throw "Invalid command";
}
}

and i call it in main:

int main(){
string input;

cin<<input;

try{
control_input(input);
}
catch(strin e){
cout<<e<<endl;
}

return 0;
}

For some reason that does not work. If it is time to catch exception, my
program ends with that kind of message:

terminate called after throwing an instance of 'std::eek:ut_of_range'
what(): basic_string::at
Aborted

What is wrong and how to make it work correctly?

You're not throwing a string (or even a std::string), you're throwing a
const char*

Oh, and there are no default return types in c++, control_input must
declare what type it returns.
 
T

Tobias Blomkvist

Juhan Voolaid sade
control_input(string input){
if(input!="open"){
throw "Invalid command";
}
}

and i call it in main:

int main(){
string input;

cin<<input;

try{
control_input(input);
}
catch(strin e){
cout<<e<<endl;
}

return 0;
}

I would argue that this is not the same code as the one you're
compiling, more likely a retype with typos, which will not compile.

Tobias
 
J

Juhan Voolaid

Hi

I have function:

control_input(string input){
if(input!="open"){
throw "Invalid command";
}
}

and i call it in main:

int main(){
string input;

cin<<input;

try{
control_input(input);
}
catch(strin e){
cout<<e<<endl;
}

return 0;
}

For some reason that does not work. If it is time to catch exception, my
program ends with that kind of message:

terminate called after throwing an instance of 'std::eek:ut_of_range'
what(): basic_string::at
Aborted

What is wrong and how to make it work correctly?



Juhan.
 
B

benben

You're not throwing a string (or even a std::string), you're throwing a
const char*

which means you have to throw like this:

throw string("ERROR: UFO found...");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,782
Latest member
ThomasGex

Latest Threads

Top