Plouff
Plouff

Reputation: 3470

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!

Upvotes: 9

Views: 52021

Answers (3)

Chad
Chad

Reputation: 19032

try
{
    throw std::runtime_error("Hi");
}
catch(std::runtime_error& e)
{
   cout << e.what() << "\n";
}

Upvotes: 11

Mark Reed
Mark Reed

Reputation: 95242

Well, it depends on what you want to do when it happens. This is the minimum:

try
{
  rapidxml::file<char> GpxFile (pcharfilename);
}
catch (...)
{
   cout << "Got an exception!"
}

If you want to get at the actual exception, then you need to declare a variable to store it in inside the parentheses in place of the three dots.

Upvotes: 1

Marlon
Marlon

Reputation: 20314

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
}

Upvotes: 21

Related Questions