top | item 40835296

(no title)

winstonewert | 1 year ago

My wish: people stop using the dumb line that exceptions are gotos.

discuss

order

wvenable|1 year ago

The pattern for returning errors is something like the following pseudocode:

    main() 
    {
         (result or error) = functionA();
         if (error) die("There was an error: " + error);
         print result
    }

    functionA() 
    {
       (result1 or error1) = functionB()
       if (error1) return error1;
       (result2 or error2) = functionC(result1);
       if (error2) return error2;
       (result3 or error3) = functionD(result2);
       return result3;
    }

     functionB()
     {
         (result or error) = readFileAndGetResult()
         if (error) return error;
         return result;
     }
Exceptions simply automate the error returns; the same code with exceptions is merely:

    main()
    {
        try {
            result = functionA();
            print result;
         } catch (error) {
             die("There was an error: " + error);
         }
     }

     functionA()
     {
         result1 = functionB()
         result2 = functionC(result1);
         result3 = functionD(result2);
         return result3;    
     }

     functionB()
     {
         return readFileAndGetResult();
     }
The most naive implementation of exceptions would do exactly what the top code does. Check for an error result from the function and return it to it's caller until it finds a catch block.

The advantage of exceptions is that you don't get the bug that exists in functionA where it fails to propagate the error from functionD. It also makes the logic of the code much more readable and writable because you don't need to put an error guard around the call to every single function.

But what is telling is that, in both examples, the error is handled in exactly the same place in the code. How can one reasonably say the second case is like a goto but the first isn't?