Error Codes

Hi ,

I need your opinions about whether to use a global return code for each method in my application or let every component throw its exception and use the upper layer to handle it.

Example :

public RetCode ABC ()

{

If(…)

Return RetCode.Valid;

Else

Return RetCode.Invalied;

}

OR

public void ABC ()

{

If(…)

Else

Throw new Exception (…);

}
Thanks




Answer this question

Error Codes

  • Tim Whtiley

    it's a best practices NOT to throw Exceptions but write code that catch common errors. So "Throw new Exception (…);" is n't the best way.

  • jhidey

    You should probably use exceptions because they force the caller to handle it whereas it is easy to forget to check a return code. There is a cost in throwing exceptions but since they are meant to be used in "exceptional circumstances" this should not be an issue.

    Consider subclassing the Exception class and add a property to store your error code:

    [Serializable()]
    public class MyCustomException : Exception {
    private RetCode _errorCode;

    public MyCustomException( string message, RetCode errorCode ) : base( message ) {
    _errorCode = errorCode;
    }

    //There are some other special constructors you should have, check the documentation for the Exception class.

    public property RetCode ErrorCode {
    get { return _errorCode; }
    }
    }


  • Peter D.252325

  • Error Codes