c ++:Catch runtime_error

Plo*_*uff 6 c++ runtime-error exception

我正在家里学习c ++而且我正在使用rapidxml lib.我正在使用它提供的utils来打开文件:

rapidxml::file<char> myfile (&filechars[0]);
Run Code Online (Sandbox Code Playgroud)

我注意到如果filechars错误则rapidxml::file抛出一个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);
Run Code Online (Sandbox Code Playgroud)

我想我需要写一些类似的东西:

try
{
  rapidxml::file<char> GpxFile (pcharfilename);
}
catch ???
{
   ???
}
Run Code Online (Sandbox Code Playgroud)

我做了一些谷歌搜索,但我找不到我需要的地方???.

有人能帮帮我吗?谢谢!

Mar*_*lon 14

您需要在catch语句旁边添加一个异常声明.抛出的类型是std :: runtime_error.

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

如果您需要捕获多种不同类型的异常,那么您可以使用多个catch语句:

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
}
Run Code Online (Sandbox Code Playgroud)


Cha*_*had 8

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