简体   繁体   中英

Exception Throwing Inconsistency

I've been playing around with error handling, and wrote a short program to try to understand exception handling. I wrote the following program where the user inputs a number, and the program catches any exceptions thrown by cin:

#include <iostream>


int main()
{

    std::cin.exceptions(std::cin.failbit);
    int ReturnCode = 0;

    try{

        float Number;
        std::cout << "Number: \n";
        std::cin >> Number;
        std::cout << Number << "\n";

    }
    catch(...){

        std::cerr << "Input error \n";
        std::cin.clear();
        char BadInput[5];
        std::cin >> BadInput;
        ReturnCode = 1;
    };

    char StopChar;
    std::cout << "Press a key and enter: \n";
    std::cin >> StopChar;

    return ReturnCode;

}

I compiled the code in Xcode, but no exception was thrown when a string was given. However, when I compiled it using terminal and the command g++ main.cpp -Wall -Wextra -o program , everything worked fine. What is going on, and what is the difference between compiling in Xcode vs. using terminal? Any help would be greatly appreciated!

It seems like a bug in libc++.

While compiling from Xcode, default setting is to use clang with libc++. Whereas g++ uses libstdc++. Setting library to libstdc++ in Xcode causes the exception to be thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM