Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ "catch (...)" parameter

Tags:

c++

arguments

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?

like image 387
zeboidlund Avatar asked Jul 19 '11 05:07

zeboidlund


People also ask

Does C have catch?

Yes, it is limited to one try-catch in the same function.

What is Catch block C?

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.

Are there try catch blocks in C?

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).

Can catch have multiple parameters?

Explanation: A catch handler should contain only one parameter of any type. Multiple parameters are not allowed inside catch handler.


1 Answers

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).

like image 89
eran Avatar answered Sep 18 '22 11:09

eran