Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: Catch runtime_error

I am learning c++ at home and I am using the rapidxml lib. I am using the utils provided with it to open files:

rapidxml::file<char> myfile (&filechars[0]);

I noticed that if filechars is wrong the rapidxml::file throw a runtime_error:

// Open stream
basic_ifstream<Ch> stream(filename, ios::binary);
if (!stream)
  throw runtime_error(string("cannot open file ") + filename);
stream.unsetf(ios::skipws);

I think I need to write something like that:

try
{
  rapidxml::file<char> GpxFile (pcharfilename);
}
catch ???
{
   ???
}

I made some googling, but I did not find what I need in the place of the ???.

Could somebody help me? Thanks!

like image 661
Plouff Avatar asked Sep 20 '11 21:09

Plouff


2 Answers

You need to add an exception declaration next to the catch statement. The type thrown is std::runtime_error.

try
{
  rapidxml::file<char> GpxFile (pcharfilename);
}
catch (const runtime_error& error)
{
   // your error handling code here
}

If you need to catch multiple, different kinds of exceptions, then you can tack on more than one catch statement:

try
{
  rapidxml::file<char> GpxFile (pcharfilename);
}
catch (const runtime_error& error)
{
   // your error handling code here
}
catch (const std::out_of_range& another_error)
{
   // different error handling code
}
catch (...)
{
   // if an exception is thrown that is neither a runtime_error nor
   // an out_of_range, then this block will execute
}
like image 158
Marlon Avatar answered Sep 29 '22 00:09

Marlon


try
{
    throw std::runtime_error("Hi");
}
catch(std::runtime_error& e)
{
   cout << e.what() << "\n";
}
like image 38
Chad Avatar answered Sep 28 '22 22:09

Chad