Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我应该对无效输入使用异常处理吗?_C++_Exception_Inputstream - Fatal编程技术网

C++ 我应该对无效输入使用异常处理吗?

C++ 我应该对无效输入使用异常处理吗?,c++,exception,inputstream,C++,Exception,Inputstream,我举了一个例子: int main() { int val{}; bool stop = false; char c; while (!stop) { std::cout << "val: "; try { if (!(std::cin >> val)) { throw std::runtime_error("bad i

我举了一个例子:

int main() {

    int val{};
    bool stop = false;
    char c;

    while (!stop) {
        std::cout << "val: ";
        try {
            if (!(std::cin >> val)) {               
                throw std::runtime_error("bad input");
            }
            std::cout << val << " : " << val * val << std::endl;
        }
        catch (std::exception& e) {
            std::cout << e.what() << std::endl;
            std::cin.clear();
            std::cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "retry\?\n>>" << std::endl;
            std::cin >> c;
            if (c != 'y' && c != 'Y')
                stop = true;
        }

    }
}
intmain(){
int val{};
bool-stop=false;
字符c;
当(!停止){
std::cout>val){
抛出std::运行时_错误(“错误输入”);
}
std::cout截取代码,显示有问题的try/throw/catch:

试试看{
如果(!(std::cin>>val)){
抛出std::运行时_错误(“错误输入”);
}

std::cout IMHO,坏输入没有异常,因此不应该使用异常。这里没有异常,非异常实现实际上会更短更清晰。好吧,这是一种设计选择,在这种情况下,答案取决于实际环境中的几个因素。无论如何,为什么你认为!std::cin
?异常被过度使用,在这种情况下,大多数情况下都是一个goto,让您感觉不写“goto”很好。您可以将其重写为一个简单的
,否则
@Biagio它不会(直接)预期
std::cin
操作会失败
    try {
        if (!(std::cin >> val)) {               
            throw std::runtime_error("bad input");
        }
        std::cout << val << " : " << val * val << std::endl;
    }
    catch (std::exception& e) {
      if ((std::cin >> val)) {                  
        std::cout << val << " : " << val * val << std::endl;
      }
      else {