Exceptions in C# - The Finally Block
(Page 4 of 4 )
And finally, the finally block. As we discussed earlier, once a catch block is executed, the other catch blocks are skipped. But what happens if we need to run a piece of code (such as closing a stream) after we catch the exception? The first answer will be to duplicate the piece of code in every catch block to make sure it executes for any type of exception. To avoid this duplication of code issue, we can use the finally block. This code will run whether there was an exception or not. We use this block to close opened streams and do the necessary clean up before we leave the method. Execute the following code first as is, then by commenting out the line a[3] = 40; //No such element:
class Program
{
static void Main( string [] args)
{
int [] a = new int [3];
try
{
a[0] = 10; //ok
a[1] = 20; //ok
a[2] = 30; //ok
a[3] = 40; //No such element.
}
catch ( IndexOutOfRangeException e)
{
Console .WriteLine( "An index out of range exception has
occurred!" );
}
catch ( ArgumentException e)
{
Console .WriteLine( "An argument exception has occurred!" );
}
catch ( ArrayTypeMismatchException e)
{
Console .WriteLine( "An array type mismatch exception has
occurred!" );
}
catch ( Exception e)
{
//printing the exception details
WriteExceptionDetails(e);
}
finally
{
Console .WriteLine( "This line executes no matter what " +
"exception was thrown. As a matter of fact this code " +
"will run even if there were no exceptions" );
//Do all the necessary clean-up and close streams here
}
}
static void WriteExceptionDetails( Exception e)
{
Console .WriteLine( "Message: {0}" , e.Message);
Console .WriteLine( "Source: {0}" , e.Source);
Console .WriteLine( "InnerException: {0}" , e.InnerException);
Console .WriteLine( "StackTrace: {0}" , e.StackTrace);
Console .WriteLine( "TargetSite: {0}" , e.TargetSite);
}
}
Conclusion
Exceptions are a powerful and clean mechanism used to track and handle errors that happen in a program. Every exception is equipped with properties and methods that return valuable information about the error. To handle exceptions, the code in question should be wrapped with a try block and followed by a list of catch blocks of exceptions that could happen. Make it a habit to always keep a finally block after the last catch block in order to do the necessary cleanup and close opened streams.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |