Exceptions - mcbride-clint/DeveloperCurriculum GitHub Wiki

The C# language's exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running. Exception handling uses the try, catch, and finally keywords to try actions that may not succeed, to handle failures when you decide that it's reasonable to do so, and to clean up resources afterward. Exceptions can be generated by the common language runtime (CLR), by .NET or third-party libraries, or by application code. Exceptions are created by using the throw keyword.

Exceptions can be very useful in passing back additional details about an error or a situation that your code is not equipped to handle. A single exception can little impact on your system's performance but if you are using many try/catch blocks with code that is throwing many exceptions, especially in a loop, then the performance can really begin to suffer. Each exception that is created will have to build a stack trace and interrupt the expected flow of the application. Use exceptions as a way to report and bubble errors to the calling code and avoid using them as ways to control the flow of your application. Using a if statement and guiding the flow will always be much more performant.


function bool ValidateStateZipCode(int zipCode, string state){
  if (zipCode == 0){
    throw new ArgumentOutOfRangeException(nameof(zipCode), zipCode, "No ZipCode Value Provided");
  }

  if (zipCode.length > 5){
    throw new ArgumentOutOfRangeException(nameof(zipCode), zipCode, "A valid ZipCode must be 5 digits")
  }

  if (string.IsNullOrWhitespace(state)){
    throw new ArgumentNullException(nameof(state), "No State Value Provided")
  }

  // Psuedo Code
  // Check whether zipcode is valid for the given state
}

The calling code can then wrap that function in a try/catch block to ensure that any exceptions will not leave their application in an undesirable state.


...

bool hasValidZipCode;

try
{
  hasValidZipCode = ValidateStateZipCode(userProvidedZipCode, userProvidedState)
}
catch (ArgumentOutOfRangeException e)
{
  return "Please correct information: " + e.Message; // Catching the different possible Exception allows you to customize your recovery behavior.
}
catch (ArgumentNullException e)
{
  return "Missing information: " + e.Message;
}

...

Repo Programming Examples:

See Also