Good evening. There is the easiest piece of code

int k = 0; for (double x = -2; x <= 2; x += 0.2) { try { mas_a[k] = sqrt(pow(x, 2) - 1); k++; } catch (EDivByZero &e) //ловим деление на 0 { mas_a[k] = 0; cout << "Деление на ноль целых чисел" << endl; k++; } catch (EZeroDivide &e) { mas_a[k] = 0; cout << "Деление на ноль вещественных чисел" << endl; k++; } cout << "[" << k << "]=>" << mas_a[k] << " | "; } 

It is necessary in the range [-2,2] in increments of 0.2 to fill the array by the function sqrt (pow (x, 2) - 1). And catch exceptions division by 0. Wrote, but swears on EZeroDivide and EDivByZero. What's wrong?

  • Do you have these classes defined? And, by the way, you still have no division by zero anyway. And, once again, by the way, there is no point in pow(x,2) - x*x and in short, and faster. - Harry
  • So what is EDivByZero and EZeroDivide ? And where do you have any throwing exceptions at all? - AnT

2 answers 2

There are no exceptions to EDivByZero and EZeroDivide . This is C ++, not delphi. Moreover, the division by 0 does not make any exception in C ++ (for built-in types). This in C ++ is not what the exceptions are responsible for, but an error for which the programmer must answer in order to avoid this.

    I propose to use in this case something like this:

     #include <iostream> #include <stdexcept> using namespace std; int main(){ try{ int i = 0; //для проверки if(!i) throw invalid_argument("division by zero"); else cout<<(double)1/i<<endl; } catch(invalid_argument& oop){ cout<<oop.what()<<endl; } return 0; }