Link to home
Start Free TrialLog in
Avatar of doitex
doitex

asked on

How to catch all exceptions?

I am trying to catch all errors, but Visual Studio in debug mode breaks execution and shows "Unhandled exception" message box. I was trying to manage Visual Studio settings (Debug->Exceptions and Tools->Options->Debuging) but it does not help to solve this.

Please help me to fix this.
#include <QtGui/QApplication>
#include <QMessageBox>
 
 
int main(int argc, char *argv[])
{
	try {
 
		int x = 0;
		int y = 4/x;
		return 1;
	}
	catch (std::exception& e) {
		QMessageBox::critical(NULL, QString("Error"),QString(e.what()));
	}
	catch (...) {
		
		QMessageBox::critical(NULL, QString("Error"),QString("Unknown error!"));
	}
 
}

Open in new window

Avatar of Infinity08
Infinity08
Flag of Belgium image

A division by zero is not a C++ exception. It's a hardware exception. You cannot catch it like that.
"Unhandled exception" here refers to a Win32 SEH exception, not a C++ Exception, see http://msdn.microsoft.com/en-us/library/ms680657.aspx ("Structured Exception Handling") on these. You can handle these like
#include <QtGui/QApplication>
#include <QMessageBox>
 
 
int main(int argc, char *argv[])
{
        __try { // <--- note the underscores
 
                int x = 0;
                int y = 4/x;
                return 1;
        }
        __except(1) {
 
                QMessageBox::critical(NULL, QString("Error"),QString("SEH Exception"));
        
        }
 
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of doitex
doitex

ASKER

jkr:

Seems "__try" can't be used with QT4 clases - see compiler error message below:

Cannot use __try in functions that require object unwinding
Ah, yes, I almost forgot that little catch - what is your exact code (since there are no classes in the above)? You might want to use the translator in this case or wrap your Objects in a function call, e.g.
        __try { 
 
                MyFunctionThatUsesQtClasses();
        }
        __except(1) {
 
                QMessageBox::critical(NULL, QString("Error"),QString("SEH Exception"));
        
        }

Open in new window

Avatar of doitex

ASKER

tnx jkr

Your solution works! I have found complete source for that:

http://www.thunderguy.com/semicolon/2002/08/15/visual-c-exception-handling/3/