The Anatomy of C# Exceptions

Exceptions allow an application to transfer control from one part of the code to another. When an exception is thrown, the current flow of the code is interrupted and handed back to a parent try catch block. C# exception handling is done with the follow keywords: try, catch, finally, and throw

  • try – A try block is used to encapsulate a region of code. If any code throws an exception within that try block, the exception will be handled by the corresponding catch.
  • catch – When an exception occurs, the Catch block of code is executed. This is where you are able to handle the exception, log it, or ignore it.
  • finally – The finally block allows you to execute certain code if an exception is thrown or not. For example, disposing of an object that must be disposed of.
  • throw – The throw keyword is used to actually create a new exception that is the bubbled up to a try catch finally block.
 
try
{

}
catch (ArgumentNullException ex)
{
//code specifically for a ArgumentNullException
}
catch (WebException ex)
{
//code specifically for a WebException
}
catch (Exception ex)
{
//code for any other type of exception
}
finally
{
//call this if exception occurs or not
}
try
{
	// Do Something That Will Fail
}
catch (Exception ex)
{
	log.ErrorFormat("Message: {0}.", ex.Message);
}

// Will Go Here
DoSomethingElse();
try
{
	// Do Something That Will Fail
}
catch (Exception ex)
{
	log.ErrorFormat("Message: {0}.", ex.Message);
	throw ex;
}

// Will NOT Go Here
DoSomethingElse();
Last modified: July 18, 2019

Author

Comments

Write a Reply or Comment