I was wondering if there is a right place to handle exceptions.
Should I handle it inside my method or should I handle it at the method call? Or does it matter at all?
I’m sorry, but I couldn’t find anything about this (googling “exception handling scope” didn’t returned what I was looking for).
Example:
// this way...
void readFile(string file)
{
try
{
/* do my stuff */
}
catch(Exception exception)
{
/* handle exception */
}
}
int main()
{
readFile(file);
}
// or this way?
void readFile(string file)
{
/* do my stuff */
}
int main()
{
try
{
readFile(file);
}
catch(Exception exception)
{
/* handle exception */
}
}
Thanks in advance.
In general you want to handle the error where it makes sense to do so.
If in your example above you want to try to read a file and if that fails then read a default file the you can handle it as in the first example.
If the readFile operation failing is vital to the rest of main() then you need to have the exception passed up to that so it can deal with whatever fallout is for readFile() failing and this would be as in your second example.
Of course you can always handle the error (or some possible exceptions) inside the method and rethrow or let some pass through or whatever.
Really though its your program flow that determines where your exception handling goes. Handle the exception where it makes sense to do so.