-
November 2nd, 2014, 01:06 AM
#1
How to handle the exceptions that couldn't be caught by try/catch?
Here is an example,
Code:
int main()
{
try{
int y = 0;
int x = 2/y;
}
catch(...)
{
cout<<"catch it"<<endl;
}
return 0;
}
If you try, you will find out that catch(...) couldn't catch exception divided by zero. How'd we catch such exceptions? Thanks.
-
November 2nd, 2014, 04:17 AM
#2
Re: How to handle the exceptions that couldn't be caught by try/catch?
When there is division by zero, the behaviour is undefined. An implementation could make it such that an exception is thrown, but this would then be implementation specific, e.g., SEH exceptions, so you would need to check your compiler's documentation.
-
November 3rd, 2014, 08:01 AM
#3
Re: How to handle the exceptions that couldn't be caught by try/catch?
some compilers have a specific (and different) synatx for handling SEH's. Typically, this type of handling can't be combined in the same function as regular C exception handling.
Some compilers have wrappers so that a SEH will end up being thrown as a specific exception type, you may need to enable this via compiler switches.
Some compilers will just wrap it in a generic untyped exception which you can catch with a catch(...), the bad thing here is that you typically don't know what type of exception it was. Again, this may need compiler switches to enable this.
none of the above is standard. So you'll either lock yourself to a specific brand/type/version of compiler, or you'll need multiple conditional code paths to handle multiple compilers.
-
November 4th, 2014, 09:17 PM
#4
Re: How to handle the exceptions that couldn't be caught by try/catch?
Originally Posted by LarryChen
If you try, you will find out that catch(...) couldn't catch exception divided by zero. How'd we catch such exceptions?
Division by 0 is not a standard C++ exception, so there is nothing to "catch" since nothing is thrown.
Regards,
Paul McKenzie
-
November 5th, 2014, 07:53 AM
#5
Re: How to handle the exceptions that couldn't be caught by try/catch?
Division by zero doesn't even have to be an exception at all.
I have several platforms where a division by zero returns... 0.
you may call that mathematically inaccurate, but in the bigger picture, the answer is just as (in)valid as an exception being thrown (which your C++ code may or may not be able to catch). THere's nothing in the C++ standard that says the above is an illegal result for a division by zero. There is a note in the C++ documentation that this happens because that's exactly how the processor itself does it since the processor doesn't support interrupts. So like said. "platform dependant".
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|