2017-03-17 70 views
1

您好我對C++編程非常陌生,我很難理解他們已經使用的代碼catch。所以我想知道他們爲什麼在這段代碼中使用catch。在此先感謝在這個C++代碼中捕獲的用法是什麼

#include <iostream> 
#include <exception> 
using namespace std; 
int main() 
{ 
try 
{ 
    int* myarray = new int[1000]; 
    cout << "allocated"; 
} 
catch (exception& e) 
{ 
    cout << "Standard exception: " << e.what() << endl; 
    } 
    return 0; 
    } 

回答

5

操作new可能拋出的情況下,不能分配所需要的空間異常。

從上面的鏈接:

throwing (1) void* operator new (std::size_t size) throw (std::bad_alloc); 

拋出bad_alloc的,如果它未能分配存儲空間。否則,它拋出 沒有任何例外(不拋出保證)。

+0

謝謝你的回答@alex –

+0

@PSFRomesh歡迎您!還有祝你好運! –

+0

注意,當'new'分配一個struct/class的實例,或者new []分配一個struct/class元素的數組時,內存可能會分配OK,但是struct/class構造函數可能拋出它自己的異常。在這個例子中情況並非如此,因爲它正在分配一個基本類型的數組。但這是值得注意的。 –

0

嘗試,趕上C++

try 
{ 

int* myarray = new int[1000]; 

    cout << "allocated"; 
} 

catch (exception& e) 
{ 

cout << "Standard exception: " << e.what() << endl; 

} 

進來的異常處理在這種情況下,首先,它西港島線使用try塊檢查內存分配,如果它無法分配內存然後使用捕獲它會拋出異常,內存不能分配