what is the use of … in c++

前端 未结 2 1197
小蘑菇
小蘑菇 2020-12-18 09:23

I tried googling ... but as expected, google ignored it.

I have this code :

try {

// some code
}

catch( ... ) {
// catch logic

}


        
相关标签:
2条回答
  • 2020-12-18 10:00

    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

    0 讨论(0)
  • 2020-12-18 10:07

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

    0 讨论(0)
提交回复
热议问题