oldSkool
oldSkool

Reputation: 1232

C#/Java exceptions vs conditional statements

Despite reading many articles (some on this board) I am still scratching my head wondering when the appropriate time to use an exception would be. I don't see many methods returning error codes in the platform API, but some people still insist that exceptions should only be used for exceptional events that require control flow to jump specifically. I have been using exceptions to handle generic conditional assertions in my programs. Is this bad practice? Or should I use the old method of returning an error code for generic failures?

Upvotes: 0

Views: 300

Answers (1)

OscarRyz
OscarRyz

Reputation: 199373

I have been using exceptions to handle generic conditional assertions in my programs. Is this bad practice?

Yes, use validation instead.

Or should I use the old method of returning an error code for generic failures?

No, use an exception instead.

So, it should be ( just saying )

if( isValidIndex()  )  {  // <-- Validation : GOOD
    return array.atPosition( x ); 
}

Instead of :

try {
   doSomethingHazzarous();
 } catch( ArrayIndexOutOfBoundsException aioobe ) {}

And it should be:

 void somethingStreange() throws IllegalStateException {
     somethingsWrongWithTheState();
 }

Instead of:

 void somethingStranger() {
    int code = somethingsWrongWithTheState(); // <-- Error code: BAD
    if ( code == SomeClass.ILLEGAL_STATE ) {
        internalFlag = SomeOther.SOME_STATE;
        return;
    }
 }

Upvotes: 4

Related Questions