By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,111 Members | 1,366 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,111 IT Pros & Developers. It's quick & easy.

exception handling problem

P: n/a
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::out_of_range'
what(): basic_string::at
Aborted

What is wrong and how to make it work correctly?

Juhan.
Aug 2 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
use stdexcept:

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

and

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

Aug 2 '05 #2

P: n/a
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

--
IMPORTANT: The contents of this email and attachments are confidential
and may be subject to legal privilege and/or protected by copyright.
Copying or communicating any part of it to others is prohibited and may
be unlawful.
Aug 2 '05 #3

P: n/a
Juhan Voolaid <ju*@hot.ee> wrote in news:42********@news.infonet.ee:
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::out_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.
Aug 2 '05 #4

P: n/a
> 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...");
Aug 3 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.