A Use Case for a Custom Exception

From OpenPetra Wiki
Jump to navigation Jump to search

Example Code Segment

Consider the following example code segment in which a Row of a DataTable is read and the content of a DataColumn is accessed:

   public class InvalidLedgerInfoException: SystemException
   {
   	public InvalidLedgerInfoException(string message, Exception innerException)
   		: base(message, innerException) 	{}
   }
   
   public class GetLedgerInfo
   {
   	int ledgerNumber;
   	private ALedgerTable ledger=null;
   	
   	public GetLedgerInfo(int ALedgerNumber)
   	{
   		ledgerNumber = ALedgerNumber;
   		ledger = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, null);
   	}
   	
   	public string RevaluationAccount
   	{
   		
   		get {
   			try {
   				ALedgerRow row = (ALedgerRow)ledger[0];
   				return row.ForexGainsLossesAccount;
   			} catch (Exception caughtException)
   			{
   				string message = 
   					"The RevaluationAccount of leger {0} could not be acquired!";
   				throw new InvalidLedgerInfoException(
   						String.Format(message, ledgerNumber), caughtException);
   			}
   		}
   	}
   	
   }

Usage Example in an Unit Test

If we proceed to write a Unit Test and in that Unit Test run the following code line for a Ledger that does not exist

 Assert.AreEqual("5003", new GetLedgerInfo(44).RevaluationAccount, "...");

we get the following result:

NestedExceptions.JPG

This means that we have the information:

Tests.MFinance.GL.TRevaluationTests.T03_GetLedgerInfo:
Ict.Petra.Server.MFinance.GL.InvalidLedgerInfoException : The RevaluationAccount of leger 44 could not be acquired!
----> System.IndexOutOfRangeException : There is no row at position 0.

Conclusion

If we would not catch the Exception and raise a Custom Exception in that situation, we would only have the following information:

  • A System.IndexOutOfRangeException has occured;
  • If the Assembly that contains the executing code has been compiled with Debug Information: the specific file and code line where the Exception has occurred.

Because we throw a Custom Exception we have the following additional information:

  • Specific Type of the Exception: Ict.Petra.Server.MFinance.GL.InvalidLedgerInfoException;
  • The RevaluationAccount of Ledger Number 44 has been requested and this request failed;

Summary: Even if the Assembly that contains the executing code has been compiled without Debug Information, we still have the user level reason for the error (wrong Ledger Number supplied) and the program level reason for the software ('There is no row at position 0').


--- Use Case prepared by Wolfgang U ---