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;
}