Handling exceptions in a method definition or call?

I was wondering if there is a suitable place to handle exceptions. Should I process it inside my method or should I process it when the method is called? Or does it matter at all?

Sorry, but I couldn’t find anything about this ("Fix exception handling" in googling did not return 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.

0
source share
5 answers

In general, you want to handle the error when it makes sense to do it.

If in your example above you want to try to read the file, and if that fails, read the default file, you can process it as in the first example.

readFile main(), , , , readFile(), , .

, ( ) - - .

, , , . , .

+4

, readFile, readFile . readFile, , :

bool readFile(string file)
{
    try {
        /* do my stuff */
        return true;
    } catch(Exception exception) {
        /* handle exception */
        return false;
    }
}
+3

, , .

, , , , . / , .

+1

, - (, , ). - (, ), ( ) - .

+1

Best practice is to allow higher levels to handle the exception. Imagine that you are packing your low-level file reader into a library and handling an exception. You do not give users of your code the ability to handle the exception in the form in which they wish.

0
source

All Articles