Details on File Processing
Exception Handling in File Processing
So far, to handle exceptions, we were using the try, catch, and throw keywords. These
allowed us to perform normal assignments in a try section and then handle an exception, if
any, in a catch block.
In the previous lesson, we mentioned that, when you create a stream, the operating system
must allocate resources and dedicate them to the file processing operations. Additional
resources may be provided for the object that is in charge of writing to, or reading from, the
stream. We also saw that, when the streaming was over, we should free the resources and
give them back to the operating system. To do this, we called the Close() method of the
variable that was using resources.
More than any other assignment, file processing is in prime need of exception handling. As we
will see in the next section, during file processing, there are many things that can go wrong. For
this reason, the creation and/or management of streams should be performed in a try block to
get ready to handle exceptions that would occur. Besides actually handling exceptions, the C#
language provides a special keyword used free resources. This keyword is finally.
The finally keyword is used to create a section of an exception. Like catch, a finally block
cannot exist by itself. It can be created following a try section. The formula used would be:
Based on this, the finally section has a body of its own, delimited by its curly brackets. Like
catch, the finally section is created after the try section. Unlike catch, finally never has
parentheses and never takes arguments. Unlike catch, the finally section is always executed.
Because the finally clause always gets executed, you can include any type of code in it but it is
usually appropriate to free the resources that were allocated earlier. Here is an example:
public class Program
static int Main(string args)