S
S
Sergo Zar2021-09-23 00:03:46
C++ / C#
Sergo Zar, 2021-09-23 00:03:46

Why does it print "terminate called after throwing an instance of 'errors'" when entering a non-number?

I'm trying to make it so that when entering a non-number, the program asks the user to enter a number again and so on until he enters a number. But it turned out that when you enter not a number, an inscription is displayed

terminate called after throwing an instance of 'errors'
.

Why is that?
The code:
1.cpp

#include <iostream>

#include "sz.h"

using namespace std;

int main(){
    system("chcp 65001 && cls");

    printf("введи число:");
    int n = sz::in_is_int();

    cout << n << endl;
    
  return 0;
}



sz.h
#include <iostream>

using namespace std;

enum errors{
    not_int = 1 // не число

};

namespace sz{
    int in_is_int(){
        int res = 0;
        try{
            cin >> res;

            if (cin.fail()){ 
                cin.clear();
                cin.ignore(32767,'\n'); 
                throw not_int;
            }
        }
        catch (int e){
            printf("Це не число. Спробуй ще раз\n");
            return in_is_int();
        }
        return res;
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ananiev, 2021-09-23
@SaNNy32

You are not catching an exception, try this

catch (errors){
            printf("Це не число. Спробуй ще раз\n");
            return in_is_int();
        }

A
Alexei No, 2021-09-23
@alien2023

You can do it stupidly if you are too lazy to handle exceptions:

int num{0};
    while(true)
    {
        std::cin >> num;
        if(std::cin.fail()) 
        {
        std::cin.clear();
        std::cin.ignore(32767, '\n');
        std::cout << "Error!\n";
        continue;
        }
        break;
    }
    
    std::cout << num << '\n';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question