簡體   English   中英

c ++:Catch runtime_error

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM