Hi,

I am trying to comprehend how exceptions work in c++. However I don't understand why a divide-by-zero exception es not caught by a catch. I attach de code to a better a explanation.

#include <iostream>
//#include <exception>
#include <string>

using namespace std;

int main () {
  int num1, num2;
  float resul;
 
  cout << "Introduce a number: ";
  cin >> num1;   //any number

  cout << "Introduce another number: ";
  cin >> num2;            //here I enter a zero

  try {
    resul = num1 / num2;
    cout << "Result is: " << resul << endl;
  }
  catch (...) {
    //cout << e.what() << endl;
    cout << "Have I registered the exception?" << endl;
  }
}

The problem is that the exception is not treated in the catch, why is this? Can't I treat this kind of exception like that?

Thanks!

I don't think arithmetic exceptions are caught, if somewhere in the code you 'throw' and exception, then it will catch it.

#include <iostream>
#include <exception>
#include <string>

using namespace std;

int main () {
  int num1, num2;
  float resul;
 
  cout << "Introduce a number: ";
  cin >> num1;   //any number

  cout << "Introduce another number: ";
  cin >> num2;            //here I enter a zero

  try {
    if ( num2 == 0 ) {
      throw("Divide-by-zero exception thrown.");
    }

    resul = num1 / num2;

    cout << "Result is: " << resul << endl;
  }
  catch (char *err) {
    cout << err;
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.