C++:捕获runtime_error

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7491877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:02:32  来源:igfitidea点击:

c++: Catch runtime_error

c++exceptionruntime-error

提问by Plouff

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

我在家里学习 C++,我正在使用 Rapidxml 库。我正在使用随它提供的实用程序打开文件:

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

I noticed that if filecharsis wrong the rapidxml::filethrow a runtime_error:

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

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!

有人可以帮助我吗?谢谢!

回答by Marlon

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

您需要在catch语句旁边添加异常声明。抛出的类型是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 catchstatement:

如果您需要捕获多种不同类型的异常,那么您可以添加多个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
}

回答by Chad

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

回答by Mark Reed

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.

如果你想得到实际的异常,那么你需要声明一个变量来将它存储在括号内而不是三个点。