How to keep the code look visually “attractive” when implementing error handling?

When writing code, I find it important that my code looks good (except that it should work well). This is well described in Code Complete (p729): "Visual and intellectual enjoyment of well-formatted code is a pleasure that few non-programmers can appreciate."

The problem is that, as soon as I got my code functionally working, and I started to introduce error handling (try-except clauses, etc.) to make it reliable, I believe this will usually ruin my well-designed code and turns it into something that is definitely not visually pleasing. The try-except statements and optional if's make the code less readable and structured.

Interestingly, is this because I am abusing or abusing error handling, or is it inevitable? Any tips or tricks to keep it beautiful?

+5
source share
4 answers

It is difficult to give you a general answer for this, since there are many different cases of error handling, so there are many different approaches to solving this problem. If you post some real world examples, you will probably get many suggestions here on how to improve the code.

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

EDIT: :

, :

 int MyFunction()
 {
    if( ErrorCheck1Passes())
    {
       if( ErrorCheck2Passes())
       {
           if( ErrorCheck3Passes())
           {
                callSomeFunction(...);
           }
           else
              return failureCode3;
        }
        else
           return failureCode2;
    }
    else
       return failureCode1;

    return 0;
 }

int MyFunction()
{
   if( !ErrorCheck1Passes())
       return failureCode1;
   if( !ErrorCheck2Passes())
       return failureCode2;
   if( !ErrorCheck3Passes())
       return failureCode3;

   callSomeFunction(...);
   return 0;
}
+5

, , , . , , , , .

, , . , .

, , ,

SaveSettingsSafe();
// 'Safe' in the sense that all errors are handled internally before returning
+1

, : . , , . , , if-then-else .

, C, . - , , . , , .

+1

It all depends on how you program. You can avoid many of these try-catch(or, as you say try-except) statements if you just perform the correct input check. Of course, it’s a lot of work to reach the majority of unwanted users, usually insert forms, etc., but it will keep your data processing procedures clean (or clean).

0
source

All Articles