Search code examples
c++exceptiontry-catchcatch-all

Confused about how can I handle several "Possible" exceptions in C++


I'm going to do something in C++, such as creating a file. In function which creates a file, I have set several exceptions for a possible failure. For instance if the file exists, if the disk is full, if the access is allowed, if the file creation ends happily etc...Now, when I want to catch them ALL, I get confused.

int file_create(std::string file_name) {...} // includes several exceptions at various points

try{
    file_create("/var/simple.txt");
}
catch(...){
   // what should I do here to have a specific control over what exception is throw?
}

I know ... is for a catch-all, but I do not if it lets a deeper investigation of the exception thrown?

I compile based on the C++011.


Solution

  • You could either do something like:

    try
    {
    //your code
    }
    catch(FirstException &e){}
    catch(SecondException &e){}
    ...
    

    Or if you just want to catch some exceptions that are defined by you, you can create a custom BaseException and then define the others as subclasses of that one.