I'm wondering which is the better way to catch exceptions that I throw: is it a __try / __except block or a try / catch block?
I'm writing in C++ and the program will only be used on Windows, so portability is not an issue.
Thanks!
It's fine practice to throw in the catch block. It's questionable practice to do so ignoring the original exception.
Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.
Try block. The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch blocks or finally block or both.
You should use if / else to handle all cases you expect. You should not use try {} catch {} to handle everything (in most cases) because a useful Exception could be raised and you can learn about the presence of a bug from it.
They are two very different things. try/catch are the familiar C++ keywords you know. __try/__except
is used to catch SEH exceptions. Exceptions raised by Windows itself, like DivisionByZero or AccessViolation. It is well described in the MSDN Library article for it.
You can also use it to catch C++ exception because it leverages the Windows SEH feature. You however can't get the thrown exception object out of it so there will be zero context if you actually want the handle the exception. Which is madness. The number one approach is to not ever catch SEH exceptions, they are always gross. If you do need to marry the two then use _set_se_translator() to convert the SEH exception to a C++ exception.
You should use a try
/catch
block.
As others have already answered, __try
/ __except
is for catching SEH (windows generated errors) not for catching general exceptions.
Most importantly, __try
and __catch
may not run C++ destructors or correctly unwind the stack when an exception is thrown.
Except in rare cases, you should never try to catch SEH exceptions.
EDIT: Well, I was positive on this (it's what I've always been told), but @Hans says that apparently there is a compiler switch you can use to change this. I think the docs on /EHa
are misleading, or at least incomplete, on what happens here. If someone finds definitive docs which prove this wrong, I'll happily remove this answer.
Even if it turns out this is false, you should still use try
and catch
simply because they are standard, while __try
and __except
are not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With