[英]c++: Catch runtime_error
我正在家里学习c ++而且我正在使用rapidxml lib。 我正在使用它提供的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!"
}
如果你想得到实际的异常,那么你需要声明一个变量来将它存储在括号内而不是三个点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.