2011-09-13 81 views
2
struct ZeroError{ 
    int err; 
    ZeroError(int e){err = e;} 
}; 


int div(int a,int b) 
{ 
    if (b == 0)throw int(10); 
    return a/b; 
} 


int main() 
{ 
    try{ 
     int x = div(10,0); 
     cout<< x; 
    } 
    catch(int z){ 
     cout<<z; 
    } 

} 

即使當我跑我得到鐺不是C++異常正常工作

程序終止叫做拋出

此應用程序已請求「詮釋」的實例後,異常被捕獲運行時以終止它在 不尋常的方式。請聯繫應用程序的支持團隊獲取更多 信息。

+1

看起來像是有例外關閉 – Nikko

+0

鏘支持在Win32異常編譯的是不存在的,但。 http://cygwin.com/ml/cygwin/2012-02/msg00015.html – legends2k

+0

你如何在叮噹中打開C++異常?例如,在msvc中,你使用'/ EHsc' – EhevuTov

回答

1

嘗試使用-fcxx-exceptions進行編譯。

對代碼做了一些清理,使用div作爲函數名與stdlib.h中的一個相沖突。還嘗試使錯誤輸出更具特色。

#include <iostream> 
#include <exception> 
using namespace std; 

struct ZeroError{ 
    int err; 
    ZeroError(int e){err = e;} 
}; 


int divide(int a,int b) 
{ 
    if (b == 0)throw int(10); 
    return a/b; 
} 


int main() 
{ 
    try{ 
     int x = divide(10,0); 
     cout << x << endl; 
    } 
    catch(int z){ 
     cout << "Exception: " << z << endl; 
    } 
} 

與標誌進行編譯,似乎偉大的工作:

% clang++ -fcxx-exceptions foo.cc 
% ./a.out 
Exception: 10 

% clang++ --version 
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) 
Target: x86_64-apple-darwin13.1.0 
Thread model: posix 
+1

這並不能解答這個問題。要批評或要求作者澄清,請在其帖子下方留言。 – sooper

+0

好點,改寫它。 – drewish