c++: Catch runtime_error

c++: Catch runtime_error

本文关键字:error runtime Catch c++      更新时间:2023-10-16

我正在家里学习c++,我正在使用rapidxml库。我正在使用它提供的utils来打开文件:

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

我注意到,如果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);

我想我需要写这样的东西:

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

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

有人能帮我吗?谢谢!

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

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

如果您需要捕获多个不同类型的异常,那么您可以添加多个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
}
try
{
    throw std::runtime_error("Hi");
}
catch(std::runtime_error& e)
{
   cout << e.what() << "n";
}

嗯,这取决于当它发生时你想做什么。这是最小值:

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

如果您想获得实际的异常,那么您需要声明一个变量,将其存储在圆括号内,以代替三个点。