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!

Edited 6 Years Ago by tikoti: n/a

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;
  }
}
This article has been dead for over six months. Start a new discussion instead.