Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

heckler0077

macrumors newbie
Original poster
Dec 10, 2008
5
0
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?
 

gnasher729

Suspended
Nov 25, 2005
17,980
5,566
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".
 

Krevnik

macrumors 601
Sep 8, 2003
4,101
1,312
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".

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.
 

Sander

macrumors 6502a
Apr 24, 2008
521
67
Granted, it may be possible that some OSes (*cough*Windows*cough*) will convert CPU interrupts like this into an exception.

I was going to say this. It leads to people getting bad habits, since it's non-standard. For a short explanation, see here.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.