I'm having trouble figuring out how to use exceptions to check if a file stream was created successfully. I know I can use if statements, but how do I do this using try/catch statements? It compiles successfully but it gives me an error when I supply a non-existent filename as an argument. If I supply a file that does exist, it runs fine. The message I get when I give it a bogus filename is:

terminate called after throwing an instance of 'char*'
Abort trap
#include <iostream>
#include <fstream>
#include <exception>

int main(int argc, char *argv[])
{
  try
  {
    std::ifstream somefile(argv[1], std::ios::in | std::ios::binary);

    if (somefile.good())
      std::cout << "Opened file!";
    else
      throw "Error opening file!";
    somefile.close();
  }

  catch (const std::exception &e)
  {
    std::cerr << e.what() << std::endl;
    exit(1);
  }
  return 0;
}

Recommended Answers

All 2 Replies

The catch() does not match the type of the exception that is thrown.

Either:

try 
    {
        std::ifstream somefile(argv[1], std::ios::in|std::ios::binary ) ;
        if( !file ) throw "Error opening file!" ; 

        // no error
        // ...
    }

    catch( const char* cstr )
    {
        std::cerr << cstr << '\n' ;
    }

or

try 
    {
        std::ifstream somefile(argv[1], std::ios::in|std::ios::binary ) ;
        if( !file ) throw std::ios::failure( "Error opening file!" ) ; 
        
        // no error
        // ...
    }
    catch( const std::exception& e )
    {
        std::cerr << e.what() << '\n' ;
    }

would be ok.

That was exactly what I was looking for. Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.