Simple exception question

hi. I started learning exceptions just now. The following program crashes without entering catch block, I was wondering why...
Any help

1
2
3
4
5
6
7
8
9
	try
	{
		int *p = NULL;
		*p = 10;
	}
	catch (...)
	{
		printf("Exception occurred");
	}
First off when using pointers you have to assign them to a variable say integer X not NULL. Second you are assigning the value pointed to by p a value even though p is not pointing to anything. This is probably what caused the crash.
Actually, it's okay to assign it null or nothing at all, but it must be assigned something before being dereferenced (*p).
And yes. Writing to NULL causes a segmentation fault and the program crashes.
Last edited on
i understand why this program crashes. I was trying to make understanding of exception. when i call *p = 10, it should pass control to catch block rather than crashing, isnt it ???
I'm not entirely sure, but segmentation faults can't be caught. The kernel detects them and terminates the guilty program before the program can react (since it's waiting confirmation from the kernel).
Technically, an exception has not occurred. You have written to invalid memory causing the application to crash. A catch is only good to catch a thrown exception.
It is an (unfortunate, IMO) part of C++'s design philosophy.

Page faults (writing to *0, invalid memory, etc.) are purposefully not caught by a try..catch block.

If you are using VC++ (or other Win32-smart compilers) you can enable SEH integration into standard exceptions.

Otherwise you'll have to roll your own. I responded similarly not too long ago (on DaniWeb):
http://www.daniweb.com/forums/thread144854.html#post687600

Hope this helps.
Topic archived. No new replies allowed.