C++ Xcode Exceptions acting as if not there

Discussion in 'Mac Programming' started by heckler0077, Dec 10, 2008.

  1. heckler0077 macrumors newbie

    Joined:
    Dec 10, 2008
    #1
    So, I'm using Xcode 3.1.1 and I've bee learning C++ for awhile now. Anyways, I'm on one of the last chapters, and it deals with exceptions.

    Code:
    #include <iostream>
    using namespace std;
    
    const int DefaultSize = 10;
    
    int main()
    {
    	int top = 90;
    	int bottom = 0;
    	
    	try
    	{
    		cout << "top / 2 = " << (top/ 2) << endl;
    		
    		cout << "top divided by bottom = ";
    		cout << (top / bottom) << endl;
    		
    		cout << "top / 3 = " << (top/ 3) << endl;
    	}
    	catch(...)
    	{
    		cout << "something has gone wrong!" << endl;
    	}
    	
    	cout << "Done." << endl;
    	return 0;
    }
    
    Everything seems to be going fine, but then, I run the code, and it throws an operating system exception telling me
    Code:
    Program received signal:  “EXC_ARITHMETIC”.
    Well, thanks, that's the exact same behavior the program showed without try/catch blocks. So, I set breakpoints and step through it. And it gets to the line where the program divides by zero, throws an operating system exception, and puts me back on the line. It's behaving as if the try/catch block don't exist. This is really strange. Does anyone know what's going on?
     
  2. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #2
    Division by zero doesn't throw an exception, it raises a signal. try/catch catches exceptions. To handle a signal, you need a signal handler. In terminal, type "man signal".
     
  3. Krevnik macrumors 68030

    Krevnik

    Joined:
    Sep 8, 2003
    #3
    Yup. What you are seeing isn't a C++ exception. There was no exception raised that C++ can handle. The CPU issued an interrupt, and the OS is using signals to let your app know what happened (and if you don't respond, kill the process so the CPU can continue executing something else).

    Granted, it may be possible that some OSes (*cough*Windows*cough*) will convert CPU interrupts like this into an exception.
     
  4. Sander macrumors 6502

    Joined:
    Apr 24, 2008
    #4
    I was going to say this. It leads to people getting bad habits, since it's non-standard. For a short explanation, see here.
     

Share This Page