开发者

clang not working properly for C++ Exceptions

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;
    }

}

even though exception is caught when i run the program i am getting

terminate called after throwing an instance of 'int'

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.


Try compiling with -fcxx-exceptions.

Did a little cleanup on your code, using div as a function name collided with one in stdlib.h. Also tried to make the error output more distinctive.

#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;
    }
}

Compiling with the flag seems to work great:

% 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜