[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

OT: g++ ignoring try/catch blocks?



I am working through a C++ tutorial and have arrived at the chapter on
exception handling.  The example program sets up a try{} catch() {} set
of blocks for catching a divide by zero exception.  The problem is that
g++ on Sid is quitting at the divide by zero statement and seemingly
ignoring the try/catch blocks.

Here is the code:

// trying and catching
#include <iostream>

const int DefaultSize = 10;


int main()
{
	int top = 90;
	int bottom = 0;

	try
	{
		std::cout << "top / 2 = " << (top / 2) << std::endl;

		std::cout << "top divided by bottom = ";
		std::cout << (top / bottom) << std::endl;

		std::cout << "top / 3 =	" << (top / 3) << std::endl;
		std::cout << "Done." <<	std::endl;
	}

	catch(...)
	{
		std::cout << "something has gone wrong!" << std::endl;
	}

	std::cout << "Done." << std::endl;

	return 0;
}


If the exception were caught, one would expect the catch() block to
print out its message, however, control is never given to that block.
Running the program results in the following output:

top / 2 = 45
Floating point exception

with the program closing immediately.  The code compiles cleanly as I
use the -Wall option to g++.  Running through GDB gives this result:

$ gdb ./list20_2
GNU gdb (GDB) 7.3-debian
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show
copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/nate/src/c++/Day_20/list20_2...done.
(gdb) run
Starting program: /home/nate/src/c++/Day_20/list20_2 
top / 2 = 45

Program received signal SIGFPE, Arithmetic exception.
0x0804884a in main () at list20_2.cc:17
17			std::cout << (top / bottom) << std::endl;
(gdb) 


Further confirming that the enclosing try{} block seems to be ignored.


Thanks!

- Nate >>

-- 

"The optimist proclaims that we live in the best of all
possible worlds.  The pessimist fears this is true."

Ham radio, Linux, bikes, and more: http://www.n0nb.us


Reply to: