Hey guys,
How do you handle exceptions in your programs? For instance, I have this function:
bool load_file(const char *filepath, std::string &dest)
throw (std::bad_alloc, std::runtime_error) {
using namespace std;
ifstream file;
file.open(filepath, ios::binary);
if (!file.good()) {
throw runtime_error("Couldn't open the file");
}
//get filesize in bytes from ifstream
//seek end, get pointer, rewind
file.seekg(0, ios_base::end);
size_t file_size = file.tellg();
file.seekg(0, ios_base::beg);
if (!file.good()) {
throw runtime_error("Fatal error while getting filesize.");
}
//read file in string from ifstream
//allocate array, read file in array, set the term. null byte, set string to array
char *file_content;
try {
file_content = new char [file_size+1];
} catch (bad_alloc &memException) {
cerr << "Probably went out of memory while allocating " << file_size+1 << " bytes!" << endl;
file.close();
throw;
}
file.read(file_content, file_size);
file_content[file_size] = '\0';
dest = file_content;
//clean up
//close file, free array
file.close();
delete[] file_content;
return true;
}
How would I handle the throw at line 7? Only with a try-catch block, or is it also possible to call the exception.what() in the terminate function?
Here's the rest of the program, I'd like to make my terminate function show what went wrong, to really have 1 central place for all the fatal errors.
#include <iostream>
#include <fstream>
#include <string>
#include <new>
#include <stdexcept>
/* load_file(filepath, destination)
-Returns whether it succeed or not. True meaning succeeded.
-Takes a path and writes to a std::string, completely memory safe.
*/
bool load_file(const char *filepath, std::string &dest)
throw (std::bad_alloc, std::runtime_error) {
--------------------cut here--------------------
return true;
}
void custom_terminate() {
std::cerr << "--Aye, unrecoverable exception thrown!\n"
<< "Try doing what the messages say (if anything) and run the program again or ask someone with a bit more expertise to help you out." << std::endl;
std::abort();
}
int main() {
using namespace std;
set_terminate(custom_terminate);
string file_content;
load_file("test.sss", file_content);
cout << file_content;
return 0;
}