2011-09-20 81 views
3

我在家学习C++,我使用的是rapidxml库。 我使用随附的说utils的打开文件:C++:Catch runtime_error

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 ??? 
{ 
    ??? 
} 

我做了一些google搜索,但我没有找到我需要在???的地方。

有人能帮助我吗? 谢谢!

回答

10

您需要在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 
} 
+0

谢谢你的详细解答。我错过了catch块中的异常类型和它的用法。所以,如果很好理解,我会尝试:catch(const runtime_error&error){cout << error.what()<< endl; }'。 – Plouff

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

谢谢,它符合什么()的用法! – Plouff

0

嗯,这取决于你想要做什么当它发生。这是起码的:

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

如果你想在实际的异常,那么你需要声明一个变量给它的括号内存储在地方的三个点的。

+0

确实我错过了例外的类型。 – Plouff

相关问题