2017-05-12 61 views
0

所以我有這樣一個問題:例外在構造函數C++

class Exception{ 
    private : string message; 
    public : 
    Exception(); 
    Exception(string str); 
    string what(); 

}; 
class Something{ 
public : Something(int m) throw(Exception); 
....} 

,並在cpp文件:

Exception::Exception() 
    { 
     message="cant divide by 0"; 
    } 
    Exception::Exception(string str) 
    { 
     message = str; 
    } 
    Exception:string what() 
    { 
     return message; 
    } 

,然後我試圖使用它的一些構造

Something::Something(int m) throw(Exception) 
    { 
     if (m==0) 
     { 
      throw Exception(); 
     } 
    }; 

and in the main

... 
catch(Exception obj){ 
    cout<<obj.what(); 

}

它顯示「Exception」沒有命名一個類型,'obj'沒有聲明,我不知道爲什麼。

+1

你'Exception'必須從'的std :: exception'繼承是在try/catch語句可用... – Charles

+4

@ C650號,例外是完全沒有問題的方式是。 – 1201ProgramAlarm

+0

你,包括你在主CPP文件中的異常頭文件? – 1201ProgramAlarm

回答

0

Exception類可以是不完整的。

它不看我像異常::什麼()是正確定義。

的Try ...

string Exception::what() 
{ 
    return message; 
} 

而且,正如其他人所提到的,在C++中,你不必定義什麼是函數拋出像Java中。看到這個問題的詳細信息...

Throw keyword in function's signature

Something::Something(int m) 
{ 
    if (m==0) 
    { 
     throw Exception(); 
    } 
}; 

而且通常我會趕上來拋出異常的引用,除非它是一個基本類型。這將避免製作一個例外的副本。

嘗試...

... 
catch(Exception& obj) { 
    cout << obj.what(); 
} 
+0

應該由常量引用可能趕上,但由於異常對象應該是一成不變的,無論如何,我想這沒有多大意義。 –