Reputation: 13309
I know that the general method for using the try catch duo is something like this:
try
{
//your code
}
catch(...)
{
//any error goes here
}
Is there a way by which catch() catches the error code without giving any input... i.e if I didn't throw an exception but the c compiler did, then the error code can be anything. I just need to catch whatever the error code is and be notified that's all.
Upvotes: 3
Views: 4163
Reputation: 363547
Apparently, you're trying to catch
errors from functions that don't throw exceptions but return numerical error codes. That's impossible. The closest you can get is wrapping all your C functions in exception throwing code yourself:
FILE *safe_fopen(char const *path, char const *mode)
{
FILE *f = std::fopen(path, mode);
if (f == NULL)
throw std::runtime_error(std::strerror(errno));
return f;
}
It is not possible to throw an exception when a program derefences a null pointer or an invalid piece of memory, at least not in a portable manner; when that happens, behavior is simply undefined. There's no error code to check for, just a segfault on most OSs.
But please get your terminology straight. The compiler does not throw an exception, a function may do so, at run-time. The C compiler has very little to do with all this.
Upvotes: 10
Reputation: 239270
You don't have to catch everything. If you only want to handle a particular type of exception, only catch that exception:
try {
} catch (MyExceptionType ex) {
}
Upvotes: 0