How to catch this error? [C++]
I'm trying to catch dividing by zero attempt:
int _tmain(int argc, _TCHAR* argv[])
{
开发者_运维知识库int a = 5;
try
{
int b = a / 0;
}
catch(const exception& e)
{
cerr << e.what();
}
catch(...)
{
cerr << "Unknown error.";
}
cin.get();
return 0;
}
and basically it doesn't work. Any advice why? Thank you. P.S. Any chance that in the future code can be placed between [code][/code] tags instead of four spaces?
Divide by zero does not raise any exceptions in Standard C++, instead it gives you undefined behaviour. Typically, if you want to raise an exception you need to do it yourself:
int divide( int a, int b ) {
if ( b == 0 ) {
throw DivideByZero; // or whatever
}
return a / b;
}
The best way would be to check if the divisor equals 0.
C++ doesn't check divide-by-zero. A brief discussion can be found here.
You appear to be currently writing code for Windows (evidence: _tmain
and _TCHAR
are not portable C++).
If you would like a solution which only works on Windows, then you can use so-called "structured exception handling" (SEH):
- Enable structured exceptions by compiling with /EHa: http://msdn.microsoft.com/en-us/library/1deeycx5.aspx
- Use
__try
,__except
and an exception filter to only catch EXCEPTION_INT_DIVIDE_BY_ZERO: http://msdn.microsoft.com/en-us/library/s58ftw19.aspx, http://msdn.microsoft.com/en-us/library/aa363082.aspx
However, this is a MS-only feature. If you rely on an exception being thrown to deal with this error, then it will take considerable effort to change your code later if you want it to work on other platforms.
It's better to write your code with an awareness of when the divisor might be 0 (just as when you do mathematics, and divide by a quantity, you must consider whether it might be 0). Neil's approach is a good low-impact solution for this: you can use his divide
function whenever you aren't sure.
精彩评论