C# Simplified, part 5: Error Handling and Files

In this article, you will learn about the two types of errors and how to handle them. You will also learn how to access files and directories, and a number of useful things you can do with those files once you have accessed them.

Contributed by
Rating: 2 stars2 stars2 stars2 stars2 stars / 15
May 31, 2005
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement
C# Simplified covers each and every concept of C# programming language in a concise manner. The articles in this series have been divided into several parts and will provide detailed explanations along with source codes and screenshots. This series has been specifically written for beginners and students with an aim to teach C# in a quickest possible time. Please send your comments to csharpsimplified@gmail.com

Not all programmers are 100 percent accurate. Errors can happen and sometimes they prove fatal. As a programmer, you have to carefully handle each and every possible error. As you may know, there are two types of errors. They are compilation and runtime. Compilation errors can be rectified during the programming phase itself. These errors can happen due to bad coding, misspelling of syntaxes and so on. They can be corrected by studying the error messages and warnings produced by the compiler.

On the other hand, runtime errors are very crucial. They will occur at the time of program execution and cannot be corrected. These errors are referred to as exceptions. A classic example of an exception is the division by zero error. If you are developing a calculator, you must provide a system for handling this error. Another classic example of an exception is overflow of arrays. Hence these kinds of errors cannot be avoided.

You as a programmer should take proper measures to avoid these exceptions at the time of coding the program. Every programming language provides some sort of technique for handling runtime errors.

You must identify the following two key aspects before starting to program with C#. They are:

  1. Finding out those parts from the source code which are most likely to cause runtime errors.
  2. Handling those errors according to C# language conventions.

As you may be aware, the base class of all exception classes in the .NET Framework is System.Exception. This class defines numerous exceptions, which are used for different purposes. Table 5.1 lists some of the important exceptions defined under this class.

Name

Description of probable cases

ArithmeticException

Data Type not matched, invalid casting etc.

DivideByZeroException

An attempt to divide a value by zero.

FormatException

Incorrect arguments for the methods.

MissingMethodException

An attempt to call an invalid method.

OutOfMemoryException

Not enough memory to complete an operation.

OverflowException

An attempt to give large values to a variable of some type.

Different ways to handle exceptions         

Exceptions in C# must be handled in a special manner, with the help of try-catch blocks and according to the C# language conventions.  

You can also apply the finally{} clause, but this is optional. Furthermore, you can create your own exceptions with the help of the throw keyword. The try block will appear only once in a program, but the catch block can appear one or more times. This is because you may have to handle more than one exception in a single program. The code inside the finally block will always execute, whether the exception has occurred or not.

Try-Catch clause

 

Before proceeding to learn the application of the try-catch clause, let’s consider a situation in which the exception is not handled properly. In listing 5.1, an attempt is made to divide a number by zero, which ultimately results in division by zero error.

Listing 5.1

using System;

class WithoutExcep

{

      public static void Main()

      {

           

            int x = 5;

            int y = 0;

            int z = x/y;

            Console.WriteLine(z);

      }

}

If you execute the above program, the C# interpreter produces a dialog box.

If you click yes, a new instance of Visual Studio .NET debugger will open up, and upon selecting No you will get an output as shown below:

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.

   at WithoutExcep.Main()

In order to avoid this error, you must wrap the portion of the above code which causes trouble with a try clause, and it should be followed by a catch clause. The statements inside the catch block are executed only when an exception occurs. The main advantage to handling this exception is that users are provided with user-friendly error messages, rather than a set of unrecognized statements and dialog boxes. Listing 5.2 is a modified version of listing 5.1. The code properly handles the possible error with a try-catch block.

Listing 5.2

using System;

class WithExcep

{

      public static void Main()

      {

            try

            {

                  int x = 15;

                  int y = 0;

                  int z = x/y;

                  Console.WriteLine(z);

            }

            catch(Exception)

            {

                  Console.WriteLine("Error occurred, unable to                            compute");

            }

      }

}

If you execute the above code, the statement inside the catch block will be printed. It will not produce an error message as you have seen above. Try to replace line 9 with the following code and observe the result:

int y = 5;

You can also retrieve system specific error messages with the help of an exception variable, along with your own error message. Listing 5.3 is a modified version of listing 5.2. The only difference is in the catch block, where I have applied a variable named e and called in the statement which encloses the catch block.  

Listing 5.3

using System;

class WithExcep2

{

      public static void Main()

      {

            try

            {

                  int x = 15;

                  int y = 0;

                  int z = x/y;

                  Console.WriteLine(z);

            }

            catch(Exception e)

            {

                  Console.WriteLine("Error occurred: \n" +e);

            }

      }

}

The resulting output of the above code is shown below:

Error occurred:

System.DivideByZeroException: Attempted to divide by zero.

   at WithExcep2.Main()

Finally clause

You have already seen from the above explanations that the statements inside the catch block will be executed only if an error occurs. However, there may be situations where something should be performed whether an exception has occurred or not. In such cases, you can make use of the finally clause, as shown in listing 5.4:

Listing 5.4

using System;

class FinallyDemo

{

      public static void Main()

      {

            try

            {

                int x = 15;

                int y = 0;

                int z = x/y;

                Console.WriteLine(z);

                }

            catch(DivideByZeroException e)

            {

                Console.WriteLine("Error occurred " +e);

                }

            finally

            {

                Console.WriteLine("Thank you for using the program");

            }

      }

}

In the above code, the statement inside the finally block will always execute. The final output looks like this:

Error occurred System.DivideByZeroException: Attempted to divide by zero.

   at FinallyDemo.Main()

Thank you for using the program

Accessing files and directories

You can access files and directories with the help of System.IO namespace. This namespace provides all the necessary classes, methods and properties for manipulating files and directories. The main classes within this namespace are listed in table 5.2

Table 5.2

Class Name

Usage

BinaryReader and BinaryWriter

To read and write primitive data types.

Directory, File, DirectoryInfo and FileInfo

To create, delete, move files and directories. Also used for getting specific information about the files with the help of various properties.  

FileStream

To access files in a random fashion.

MemoryStream

To access data stored in memory.

StreamWriter and StreamReader

To read and write textual Information.

StringReader and StringWriter

To read and write textual information from a string buffer.

Working with FileInfo and DirectoryInfo classes

FileSystemInfo is the base class of FileInfo and DirectoryInfo classes. FileSystemInfo is an abstract class. This means that you can’t instantiate this class directly. You can create instances of the classes inheriting from it and also make use of the various properties and methods. Table 5.3 lists some of the important properties of the FileSystemInfo class

Table 5.3

Properties

Usage

Attributes

Returns attributes associated with a file. Takes FileAttributes enumeration values.

CreationTime

Returns the time of creation of the file.

Exists

Used to check if a supplied file is a directory or not.

Extension

Used to return the file extension.

LastAccessTime

Returns last accessed time of the file or the directory.

FullName

Returns the full path of the file or the directory.

LastWriteTime

Returns the time of last written activity to the file.

Name

Returns the name of a given file.

Delete()

This method is used to delete a file.

Listing 5.4 creates an instance of the DirectoryInfo class, and the code in listing 5.5 shows how to apply some of the above properties. 

Listing 5.4

DirectoryInfo dirinfo = new DirectoryInfo(@”C:\WINDOWS”);

Listing 5.5

using System;

using System.IO;

      class DirectoryDemo

      {

            public static void Main()

            {

               DirectoryInfo dirinfo = new DirectoryInfo(@"C:\WINDOWS");

               FileInfo finfo = new FileInfo("D:\Test.txt");

               Console.WriteLine("Full Name is: {0}", dirinfo.FullName);

               Console.WriteLine("Time of Creation : {0}", dirinfo.CreationTime);

               Console.WriteLine("Attributes are : {0}", dirinfo.Attributes.ToString());

               Console.WriteLine("Full Name is: {0}", finfo.FullName);

              

             

            }

      }

Displaying all files under a directory

It is very easy to populate all files within a directory by using C#. All you need to do is create an instance of DirectoryInfo class and call the GetFiles() method. Since you are displaying all the files, you must use the foreach() loop. Listing 5.6 shows you how to display all jpeg files under a particular directory.

Listing 5.6

DirectoryInfo dir = new DirectoryInfo(@”F:\WINNT”);

FileInfo[] bmpfiles = dir.GetFiles(“*.bmp);

Console.WriteLine(“Total number of bmp files” , bmpfiles.Length);

Foreach( FileInfo f in bmpfiles)

{

Console.WriteLine(“Name is : {0}”, f.Name);

Console.WriteLine(“Length of the file is : {0}”, f.Length);

Console.WriteLine(“Creation time is : {0}”, f.CreationTime);

Console.WriteLine(“Attributes of the file are : {0}”, f.Attributes.ToString());

}

Creating Subdirectories

C# enables you to programmatically create a subdirectory with the help of the CreateSubDirectory() method. In listing 5.7, a subdirectory named MYSUB is created under SUB directory. The new directory will be created on the D drive of your system.

 

Listing 5.7

using System;

using System.IO;

      class CreateDir

      {

            public static void Main()

            {

                 

                  DirectoryInfo dir = new DirectoryInfo(@"D:\");

                  try

                  {

                     dir.CreateSubdirectory("SUB");

                     dir.CreateSubdirectory(@"SUB\MYSUB");

                  }

                  catch(IOException e)

                  {

                     Console.WriteLine(e.Message);

                  }

            }

      }

After executing the above code, go to the D drive and verify the existence of the newly created directories.

Creating files

With C#, you can create new files with the help of the Create() method of the FileInfo class. You can also access specific information about the file. You can even delete a file. In listing 5.8, a file named Mycsharp.txt is created on the D drive of your system. After creating the file, the program displays some useful properties.

Listing 5.8

using System;

using System.IO;

      class CreateFile

      {

            public static void Main()

            {

              

               FileInfo finfo = new FileInfo(@"D:\Mycsharp.txt");

               FileStream fstream = finfo.Create();

               Console.WriteLine("File Mycsharp.txt created");

               Console.WriteLine("Creation Time: {0}",finfo.CreationTime);

               Console.WriteLine("Full Name: {0}",finfo.FullName);

               Console.WriteLine("FileAttributes: {0}",finfo.Attributes.ToString());

               fstream.Close();

              

            }

      }

You can verify the existence of the file by going to the D drive using My Computer or Windows Explorer.

Listing 5.9 is a continuation of listing 5.8. After creating the file, the program will ask you to press any key to delete the file. If you press a key the file system will close, and the created file will be deleted from your system.

Listing 5.9

using System;

using System.IO;

      class CreateFile

      {

            public static void Main()

            {

              

               FileInfo finfo = new FileInfo(@"D:\Mycsharp.txt");

               FileStream fstream = finfo.Create();

               Console.WriteLine("File Mycsharp.txt created");

               Console.WriteLine("Creation Time: {0}",finfo.CreationTime);

               Console.WriteLine("Full Name: {0}",finfo.FullName);

               Console.WriteLine("FileAttributes: {0}",finfo.Attributes.ToString());

               Console.WriteLine("Press any key to delete the file");

               Console.Read();

               fstream.Close();

               finfo.Delete();

               Console.WriteLine("File Mycsharp.txt deleted");

            }

      }

Reading from a file

You can read the contents of a file using the StreamReader class. The file name should be passed as a parameter to the OpenText() method of the File class. A loop is then created to read the file using the ReadLine() method, and the output is printed on to the console. The code in listing 5.10 helps you to understand the process in detail.

Listing 5.10

using System;

using System.IO;

      class ReadFile

      {

            public static void Main()

            {

               

                Console.WriteLine("Reading the contents....");

                try

                {

                  StreamReader sr = File.OpenText("G:\\Demo.txt");

                  string readfile = null;

                  while ((readfile = sr.ReadLine()) != null)

                  {

                     Console.WriteLine(readfile);

                  }

                }

                catch

                {

                     Console.WriteLine("The specified file dosen't exist"); 

                       Console.WriteLine("Please try again by changing the file name");

                }

                

              

            }

      }

In the above code, a necessary exception is handled by using a try-catch block. Hence the program will show errors if you pass an invalid error name or a file name which does not exist. 

Writing to a file

Like the StreamReader class, .NET Framework also provides the StreamWriter class, with which you can write content to a file. It is not necessary for you to create a file before writing content to it. C# automatically creates the file while executing the application. In listing 5.11, three lines of text are written to a file named WriteDemo.txt. The file name is passed as a parameter to an instance of FileInfo class. Then an instance of StreamWriter is created using the CreateText() method of FileInfo class. A series of statements are printed to the file using the WriteLine() method of StreamWriter class. Fnally, the file stream is closed with the help of Close() method.

Listing 5.11

using System;

using System.IO;

      class WriteFile

      {

          public static void Main()

          {

           

            FileInfo fi = new FileInfo("D:\\WriteDemo.txt");

            StreamWriter sw = fi.CreateText();

           

            sw.WriteLine("Welcome");

            sw.WriteLine("To");

            sw.WriteLine("C-Sharp");

            sw.Write(sw.NewLine);

            Console.WriteLine("Please open the file to view the contents");

            sw.Close();

          }

      }

Copying a file

C# enables you to copy the entire contents of a file to another file with the help of the Copy() method of the File class. In listing 5.12, the content of Hello.cs is copied to a file named Hello_new.cs located on the same drive.

Listing 5.12

using System;

using System.IO;

      class FileCopy

      {

            public static void Main()

            {

               try

               {

                 

                  File.Copy("G:\\Hello.cs", "G:\\Hello_new.cs");

                 

               }catch(Exception e)

               {

                  Console.WriteLine("Error occured " +e);

               }

            }

      }

You cannot copy a file which already exists. That’s why I have applied an exception to the above code.

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 6 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials