嘗試捕捉是異常處理的方式:
try
{
// Do work in here
// If any exceptions are generated then the code in here is stopped.
// and a jump is made to the catch block.
// to see if the exception can be handled.
// An exception is generated when somebody uses throw.
// Either you or one of the functions you call.
// In your case new can throw std::bad_alloc
// Which is derived from std::runtime_error which is derived from std::exception
}
// CATCH BLOCK HERE.
catch塊中,可以定義要處理什麼異常。
// CATCH BLOCK
catch(MyException const& e)
{
// Correct a MyException
}
catch(std::exception const& e)
{
// Correct a std::exception
// For example this would cat any exception derived from std::exception
}
你可以有任意數量的catch塊,只要你喜歡。如果你的異常與catch語句中的任何catch語句匹配,那麼將執行相關的代碼塊。如果沒有catch表達式匹配一個異常,那麼堆棧將被展開,直到它找到一個更高級別的catch塊並且進程被重複(如果沒有找到匹配的catch塊,這可能導致應用程序退出)。
注意:如果多個catch表達式匹配,則使用詞法上的第一個。只有一個或沒有任何catch塊會被執行。如果沒有,那麼編譯器會尋找更高級別的try/catch。
還有一個catch子句的任何
catch(...)
{
// This is a catch all.
// If the exception is not listed above this will catch any exception.
}
那麼這是如何應用到你的代碼。
int main()
{
char *ptr;
try
{
// This calls ::new() which can potentially throw std::bad_alloc
// If this happens then it will look for a catch block.
ptr = new char[ 1000000000 ];
// If the ::new() works then nothing happens and you pointer `ptr`
// is valid and code continues to execute.
}
catch(…)
{
// You only have one catch block that catches everything.
// So if there are any statements that generate an exception this will catch
// the excetption and execute this code.
cout << "Too many elements" << endl;
}
// As you have caught all exceptions the code will continue from here.
// Either after the try block finishes successfully or
// After an exception has been handled by the catch block.
return 0;
}
這是C++ [異常處理](http://www.parashift.com/c++-faq-lite/exceptions.html)。另一個鏈接是在這裏:http://msdn.microsoft.com/en-us/library/6dekhbbc.aspx – birryree
這是一個很多方面的可怕的例子。洗你的眼睛,然後閱讀文檔。 – bmargulies
FWIW如果您不熟悉C++,那麼我不會介入異常處理和異常 – AJG85