Re: exception error
mattia.lipreri@gmail.com wrote:
#include "stdexcept"
It's <stdexcept>. Further you are missing headers for the streams and you
need to import a few names from 'std' which you use unqualified lateron.
For such examples, I wouldn't bother even adding any headers at all, but if
you do, at least try to do it right. Test-compile the code if it's supposed
to be complete.
float f;
try{
cout << "Insert value:" << endl;
cin >> f;
}catch( runtime_error err){
cout << err.what();
}
what's happen if the user will insert a string instead of a float?
Nothing, istream doesn't signal failures with exceptions except if you
explicitly configured it to (please see the interface of it for how to do
that). Rather, you should do this to detect failure:
if(!(in>>f))
// handle reading/parsing error here
Alternatively, you could read a whole line and parse it separately:
std::string line;
if(!getline( std::cin, line))
throw std::runtime_error("failed to read line");
float f = boost::lexical_cast<float>(line);
Note that the lexical cast will throw an exception, too. You then catch
these using
catch( std::exception const& e)
{ ... }
Note that a) I'm catching the baseclass here and b) I'm catching a
reference-to-const.
Uli
--
Sator Laser GmbH
Gesch?ftsf?hrer: Ronald Boers, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]