I recently saw something interesting in some c++ code:
try {
//doStuff
} catch ( ... ) {
//doStuff
}
The "..." is what I'm referring to.
Now, at first glance one might think that this is nothing more than a filler, like a comment similar to the "doStuff" we see. The weird thing is that typing this in the Eclipse CDT actually works, without giving any syntax errors.
Is there a special purpose for this at all?
Yes, it is limited to one try-catch in the same function.
catch: Represents a block of code that is executed when a particular exception is thrown. throw: Used to throw an exception. Also used to list the exceptions that a function throws but doesn't handle itself.
A try block is the block of code in which exceptions occur. A catch block catches and handles try block exceptions. The try/catch statement is used in many programming languages, including C programming language (C++ and C#), Java, JavaScript and Structured Query Language (SQL).
Explanation: A catch handler should contain only one parameter of any type. Multiple parameters are not allowed inside catch handler.
As others have mentioned, it catches everything. From what I've seen, this is mostly used when you can't identify the actual exception that is thrown. And this could happen if that exception is a Structured Exception, which is not a C++ one. For instance, if you try to access some invalid memory location. It is usually not a good habit to use those "catch all"s. You don't have a (portable) way to get a stack trace, and you don't know anything about the exception thrown.
Using this for reasons other than examples or very trivial cases might indicate the author is trying to hide the program's instability by not taking proper care of unrecognized exceptions. If you ever face such a case, you better let the program crash, and create a crash dump you can analyze later. Or, use a structured exception handler (In case you're using VS - don't know how this is done on other compilers).
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