what is the use of ... in c++ - c++

I tried googling ... but as expected, google ignored it.
I have this code :
try {
// some code
}
catch( ... ) {
// catch logic
}
I'm guessing that ... means any kind of exceptions, am I right ?
any other usages for this ?

I am aware of three use cases:
Variable number of arguments like 'printf(const char* fmt, ...)'
A catch anything as 'catch(...)'
A variadic template like 'template < typename ...T >' and unpacking 'T ...' (c++11)
And another one, which I missed, is preprocessing: variadic macros

Yes you are correct, catch(...) means to catch all the exceptions. However it is a good practice to catch exceptions by const reference. Like
catch(std::exception const & ex)
{
//code here
}
From MSDN remarks section:
Remarks:-
The code after the try clause is the guarded section of code. The
throw expression throws (raises) an exception. The code block after
the catch clause is the exception handler, and catches (handles) the
exception thrown by the throw expression if the type in the throw and
catch expressions are compatible. For a list of rules that govern
type-matching in catch blocks, see _. If the catch statement
specifies an ellipsis (...) rather than a type, the catch block
handles any type of exception, including C exceptions and system- or
application-generated exceptions such as memory protection, divide by
zero, and floating-point violations. Because catch blocks are tried in
program order, such a handler must be the last handler for its try
block. Use catch (…) with caution; typically such a catch block is
used to log errors and perform any special cleanup prior to stopping
program execution. Do not allow a program to continue unless the catch block knows how to >handle the specific exception that is caught.
try {
throw CSomeOtherException();
}
catch(...) { // Catch all exceptions – dangerous!!!
// Respond (perhaps only partially) to exception
throw; // Pass exception to some other handler
}
any other usages for this ?
One which I have seen is the usage in variable number of arguments like 'printf(const char* x, ...)'

Related

Should Lippincott functions be declared noexcept?

EDIT: Another way to ask this question, in perspective, is to ask: Should Lippincott functions "catch all"?
Should Lippincott functions be declared noexcept?, does it matter?
After all, a version of this function in which all exceptions are captured, by definition cannot produce an exception.
However, in all the examples I see online, the noexcept is never there and I was wondering if I was missing something.
Example case:
foo_Result lippincott() noexcept???
{
try {
throw;
} catch (const MyException1&) {
return FOO_ERROR1;
} catch (const MyException2&) {
return FOO_ERROR2;
} catch (...) {
return FOO_UNKNOWN;
}
}
foo_Result foo_dothing() {
try {
foo::DoThing();
return FOO_OK;
}
catch (...) {
return lippincott();
}
}
Not all catch (...) executions come from a C++ exception. It is typically advisable to rethrow the exception in any catch-all block. This would imply that lippincott should not be noexcept and also just not have the catch-all block.
Specifically, in the ABI commonly used for C++ outside of Windows, forced unwinding may execute catch-all blocks:
A catch-all block may be executed during forced unwinding. For
instance, a longjmp may execute code in a catch(...) during stack
unwinding. However, if this happens, unwinding will proceed at the end
of the catch-all block, whether or not there is an explicit rethrow.
In particular, with GCC on Linux, the blocks are executed, and if not rethrown, the application is terminated. Forced unwinding can happen even in code you completely control on POSIX if you ever call cancellation points (e.g. read).
Aside from this, it's not uncommon for a library to execute user code (e.g. think qsort). You also usually don't want to suppress those exceptions.
Therefore, the best generic option is to be transparent in catch-all blocks. Perform the cleanup you need. Then always rethrow.
So your function would look something like:
foo_Result lippincott()
{
try {
throw;
} catch (const MyException1&) {
return FOO_ERROR1;
} catch (const MyException2&) {
return FOO_ERROR2;
} catch (const FooBaseException&) {
return FOO_UNKNOWN;
}
}
GCC does allow catching forced unwinds, so if you really wanted a catch-all and the other consideration is discarded (e.g. no user callbacks), you can first catch abi::__forced_unwind and rethrow.

C++ - Do not understand the syntax of the catch function in try-catch

I've been learning about the try-catch block in C++ and I don't understand the syntax of the catch function. On cppreference, it says the following:
1) To declare a formal parameter in the catch clause:
catch (const std::exception& e) { /* */ }
2) To declare an unnamed parameter:
catch (const std::exception&) { /* */ }
3) To write a "catch-all handler" (not sure what this means), which is activated for any exception:
catch (...) { /* */ }
Questions:
1) What is the difference between these catch blocks? I'm not sure how a formal parameter, unnamed parameter, and a "catch-all handler" differ.
2) What type is the parameter e of the catch clause? Is it of type exception? I've never seen this type used other than in examples on how to write a try-catch block. If so, how could I use it in a catch clause to, let's say, output an error message? Can e accept a string I've sent in when I throw an error?
3) I've experimented and written a try-catch block as follows:
#include <iostream>
#include <string>
#include <stdexcept>
try
{
throw invalid_argument("Error, program stopped.");
}
catch(const string& e)
{
cout << e;
}
This code successfully calls the catch block and prints my message: "Error, program stopped.". However, the .exe suddenly stops working and crashes. I don't know if this is normal when an exception is thrown, or if my code is bad.
catch (const std::exception& e) { /* */ }
You need to use a named exception if you want to be able to access the exception object in the catch block. For example if you wanted to print e.what().
catch (const std::exception&) { /* */ }
You can use an un-named exception if you don't need to access the exception object. Maybe you don't care about the contents of the exception, and you just want to handle all exceptions (of this type) in the same way.
catch (...) { /* */ }
C++ allows you to throw an object of any type, whether or not it is of a type derived from std::exception. This type of catch block will catch anything thrown. Just like the un-named exception, you will not have access to the thrown object. But also, you won't even have any way to know what type it is.
For your final example, I don't think it is your catch block that is printing the message. After all, you're catching the wrong type. Some compilers will automatically insert exception catching code that will catch anything that escapes main, and if it is a type derived from std::exception, it will print the result of what(), before terminating the program. I believe GCC does this, but Visual Studio does not. Not sure about Clang or any other compilers.

c++ exception handling

Learning "try & catch". What is wrong with the following code?
Thanks for the advice.
Error in execution:
terminate called without an active exception
Aborted
The code:
#include <stdio.h>
int main()
{
int a = 3;
try
{
if (a < 5)
throw;
}
catch (...)
{
printf ("captured\n");
}
return 0;
}
Your throw; statement tries to rethrow a current exception but there probably isn't one. You need something like
throw some_exception_object();
Inside of a try block, you have to specify what to throw. The only place you can use throw by itself is inside of a catch block to re-throw the current exception. If you call throw by itself without a current exception being active, you will kill your app, as you have already discovered.
Try this:
#include <stdio.h>
int main()
{
int a = 3;
try
{
if (a < 5)
throw 1; // throws an int
}
catch (...)
{
printf ("captured\n");
}
return 0;
}
You can throw anything you want, as long as you throw something.
There are four things, two major and two minor. One thing at a time...
1. Rethrow usage w/o active exception
A throw; statement is used to re-throw an exception that is currently caught. For example:
try {
do_something();
} catch (const std::exception &) {
throw; // This statement re-throws an exception that was caught in this "catch" block.
}
In your case, you are using throw; without catching any exceptions (in order words — it does not appear inside catch block directly or indirectly), thus your program is terminated. When there is a need to throw and not to re-throw an exception, like in your case, you must specify an exception object to be thrown. For example:
throw std::runtime_error("Something bad happened");
2. catch-all clause which does not re-throw a caught exception
Your catch-all clause (catch (...)) is perfectly legal C++. However, it does not re-throw caught exception. Even though it is a legal C++ code, such a usage is a taboo. C and C++ runtime is usually using special types of exceptions to implement certain functionality. For example, NPTL is using exceptions to implement a thread cancellation. If you catch that exception using catch (...), a thread won't be cancelled and you are going to have a bad time. Generally, you have to catch exceptions by their types. In almost all cases, exceptions are inherited from std::exception, and so you have to write catch (const std::exception &) or, if you expect to catch an exact type, - catch(const TypeYouExpect &). If you must, however, use catch-all, remember to re-throw. For example:
try {
do_something();
} catch (...) {
throw; // DO NOT FORGET TO RE-THROW.
}
3. Header naming...
You are including C header whereas C++ provides its own headers for standard C features. So, header:
#include <stdio.h>
.. should be:
#include <cstdio>
C++ specific C functions get special treatment. For example, they become available in std namespace. So that you can use std::open() instead of just open() or ::open(). No big deal, but is highly recommended way to go.
4. Return from main.
Unlike C, C++'s main() function is very special. It allows you not to have return 0;. This is a default behavior. So, unless you really need to return some value, you may save yourself some time by not typing return 0;. Remember, however, that main is the only function like that, and that everywhere else you must explicitly return something unless a function is marked void.
Hope it helps. Good Luck!
You need to actually throw some object. Even something as simple as
throw "error";
will catch the error like you want it to.
see it in action here
The statement to throw an exception is:
throw <expression>;
This statement:
throw;
is also called the re-throw statement and is use to re-throw an existing exception that has been caught. It is typically used in a catch block, for example, you look at the exception and decide if you can continue, retry or abort. In case you decide to abort, you re-throw the exception so that somebody else down the call stack will catch it and handle this error.
For example:
// getResult() calls can fail with a deadlock exception
// This method will retry up to 3 times before failing
Result getResultWithRetry()
{
int nbTry = 3;
for(;;) {
try {
return getResult();
} catch (DeadLockException& e) {
if (nbTry == 0) {
throw; // re-throw the deadlock exception
}
}
--nbTry;
}
}

C++ try / catch (new to programming and not much info about this clause)

I am new to programming and am having trouble with try / catch clauses.
Here is an example from a textbook that I have:
int main( )
{
char *ptr;
try {
ptr = new char[ 1000000000 ];
}
catch( … ) {
cout << "Too many elements" << endl;
}
return 0;
}
I have tried to look online for a further explanation and the textbook does not exactly tell me what what these clauses actually do or what it is used for.
Any information would be helpful.
EDIT: The textbook I am using is:
C++: Classes and Data Structures by Jeffrey Childs
A try-catch is the C++ construct for exception handling. Google 'C++ exceptions'.
Try catch is a way of handling exceptions:
try
{
// Do work in here
// If any exceptions are generated then the code in here is stopped.
// and a jump is made to the catch block.
// to see if the exception can be handled.
// An exception is generated when somebody uses throw.
// Either you or one of the functions you call.
// In your case new can throw std::bad_alloc
// Which is derived from std::runtime_error which is derived from std::exception
}
// CATCH BLOCK HERE.
The catch block is where you define what exceptions you want to handle.
// CATCH BLOCK
catch(MyException const& e)
{
// Correct a MyException
}
catch(std::exception const& e)
{
// Correct a std::exception
// For example this would cat any exception derived from std::exception
}
You can have as many catch blocks as you like. If you exception matches any of the catch expressions in the catch statement then the associated block of code is executed. If no catch expressions matches an exception then the stack is unwound until it finds a higher level catch block and the processes is repeated (this can cause the application to exit if no matching catch block is found).
Note: If multiple catch expressions match then the lexically first one is used. Only one or none of the catch blocks will be executed. If none then the compiler will look for a higher level try/catch.
There is also a catch anything clause
catch(...)
{
// This is a catch all.
// If the exception is not listed above this will catch any exception.
}
So how does this apply to your code.
int main( )
{
char *ptr;
try
{
// This calls ::new() which can potentially throw std::bad_alloc
// If this happens then it will look for a catch block.
ptr = new char[ 1000000000 ];
// If the ::new() works then nothing happens and you pointer `ptr`
// is valid and code continues to execute.
}
catch( … )
{
// You only have one catch block that catches everything.
// So if there are any statements that generate an exception this will catch
// the excetption and execute this code.
cout << "Too many elements" << endl;
}
// As you have caught all exceptions the code will continue from here.
// Either after the try block finishes successfully or
// After an exception has been handled by the catch block.
return 0;
}
Try-catch blocks are used to trap errors in the code.
At the most basic level, errors occur because the program tries to execute an invalid instruction. That instruction (read: line of code) could be invalid for a number of reasons. In your specific instance, the instruction could be invalid if your program was not able to allocate 1,000,000,000 bytes of memory to story your ptr. The most common exception is trying to access a bad pointer, which is called a Null Pointer Exception, which occurs when you try to perform some action on an Object that either has not been created, or has been deleted (or got corrupt). You will learn to hate that exception.
Using catch(...) tells the program to execute the code inside the catch block if any error occurs inside the code within the try block. There you can handle your error and try to find someway to either fix the error condition or gracefully exit that module.
You can also catch specific errors, which you can find out more about here : http://www.cplusplus.com/doc/tutorial/exceptions/
If you already know C, try/catch achieves the same thing as setjmp/longjmp when used for error handling. Think of try as code for the if condition of setjmp and catch code for else of setjmp. This makes longjmp equivalent to throw in C++, which is used to throw an exception. In your example, probably, the new operator, which calls some memory allocation function internally, throws an exception on seeing a very large number as input by using the C++ throw operator.
void a()
{
.......
longjmp(buf,1); // <--- similar to throw
.......
}
if ( !setjmp(buf) ) // <--- similar to try
{
.......
a();
.......
}
else // <--- similar to catch
{
.......
}
try/catch is a bit more sophisticated than setjmp/longjmp, as for setjmp/longjmp you will need to declare variables which are modified in between setjmp/longjmp calls as volatile, which is not necessary for try/catch.

How can I catch all types of exceptions in one catch block?

In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?
catch (...)
{
// Handle exceptions not covered.
}
Important considerations:
A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions.
catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program.
Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the RAII pattern if you choose this route.
You don't want to be using catch (...) (i.e. catch with the ellipsis) unless you really, definitely, most provable have a need for it.
The reason for this is that some compilers (Visual C++ 6 to name the most common) also turn errors like segmentation faults and other really bad conditions into exceptions that you can gladly handle using catch (...). This is very bad, because you don't see the crashes anymore.
And technically, yes, you can also catch division by zero (you'll have to "StackOverflow" for that), but you really should be avoiding making such divisions in the first place.
Instead, do the following:
If you actually know what kind of exception(s) to expect, catch those types and no more, and
If you need to throw exceptions yourself, and need to catch all the exceptions you will throw, make these exceptions derive from std::exception (as Adam Pierce suggested) and catch that.
If you are on windows and need to handle errors like divide by zero and access violation you can use a structured exception translator. And then inside of your translator you can throw a c++ exception:
void myTranslator(unsigned code, EXCEPTION_POINTERS*)
{
throw std::exception(<appropriate string here>);
}
_set_se_translator(myTranslator);
Note, the code will tell you what the error was. Also you need to compile with the /EHa option (C/C++ -> Code Generatrion -> Enable C/C++ Exceptions = Yes with SEH Exceptions).
If that doesn't make sense checkout the docs for [_set_se_translator](http://msdn.microsoft.com/en-us/library/5z4bw5h5(VS.80).aspx)
If catching all exceptions - including OS ones - is really what you need, you need to take a look at your compiler and OS. For example, on Windows you probably have "__try" keyword or compiler switch to make "try/catch" catch SEH exceptions, or both.
Make all your custom exception classes inherit from std::exception, then you can simply catch std::exception. Here is some example code:
class WidgetError
: public std::exception
{
public:
WidgetError()
{ }
virtual ~WidgetError() throw()
{ }
virtual const char *what() const throw()
{
return "You got you a widget error!";
}
};
In C++, the standard does not define a divide-by-zero exception, and implementations tend to not throw them.
You can, of course, use catch (...) { /* code here */ }, but it really Depends On What You Want To Do. In C++ you have deterministic destructors (none of that finalisation rubbish), so if you want to mop up, the correct thing to do is to use RAII.
For example. instead of:
void myfunc()
{
void* h = get_handle_that_must_be_released();
try { random_func(h); }
catch (...) { release_object(h); throw; }
release_object(h);
}
Do something like:
#include<boost/shared_ptr.hpp>
void my_func()
{
boost::shared_ptr<void> h(get_handle_that_must_be_released(), release_object);
random_func(h.get());
}
Create your own class with a destructor if you don't use boost.
You can use catch(...) to catch EVERYTHING, but then you don't get a an object to inspect, rethrow, log, or do anything with exactly. So... you can "double up" the try block and rethrow into one outer catch that handles a single type. This works ideally if you define constructors for a custom exception type that can build itself from all the kinds you want to group together. You can then throw a default constructed one from the catch(...), which might have a message or code in it like "UNKNOWN", or however you want to track such things.
Example:
try
{
try
{
// do something that can produce various exception types
}
catch( const CustomExceptionA &e ){ throw e; } \
catch( const CustomExceptionB &e ){ throw CustomExceptionA( e ); } \
catch( const std::exception &e ) { throw CustomExceptionA( e ); } \
catch( ... ) { throw CustomExceptionA(); } \
}
catch( const CustomExceptionA &e )
{
// Handle any exception as CustomExceptionA
}
If I recall correctly (it's been a while since I've looked at C++), I think the following should do the trick
try
{
// some code
}
catch(...)
{
// catch anything
}
and a quick google(http://www.oreillynet.com/pub/a/network/2003/05/05/cpluspocketref.html) seems to prove me correct.