C# Exception Handling: An Essential Tool to Handle Runtime Errors

c# exception handlingC# is a simple modern and object-oriented programming language which part of the Microsoft .Net Framework. This language resembles C++ and is easy to learn. Its a structured language which enables you to write efficient programs. It runs on variety of computer platforms and architectures. It supports multi-threading and has provision for automatic garbage collection. Today we look at an important feature of C# which is exception handling. We assume that you are familiar with basic C# programming. If not, we recommend you take this introductory C# course to begin with.

What is Exception Handling

An exception is an error which occurs during the execution of a program. A typical example of an exception is an attempt to divide a number by zero in a running program. There are four important keywords in C# exception handling. They are as follows.

  1. try– This keyword is used to enclose a block from which exceptions may arise. It is usually followed by one or more catch blocks.
  2. catch – This is used to catch exceptions. A program catches an exception using an exception handler at the place where you wish to handle the exception. Note that you can write multiple catch statements.
  3. finally– Regardless of whether an exception is thrown or not thrown, the code enclosed by the finally block is executed in a program.
  4. throw– The throw keyword is used to throw an exception wherever there is a problem in the program. Any object can be thrown if it is either directly or indirectly derived from the System.Exception class

It is possible to define your own exceptions in the C# programming language. To do this you have to derive the user-defined exceptions from the ApplicationException class. To learn more about this advanced aspect of C#, take this course.

Syntax of Exception Handling

The syntax of C# Exception Handler looks like this.

try
{
}
catch( ExceptionName a1 )
{
}
catch( ExceptionName a2 )
{
}
catch( ExceptionName aN )
{
}
finally
{
}

Example 1: Program to Catch the DivideByZeroException

using System;
namespace ErrorHandlingApplication
{
class Divbyzero
{
int result;
Divbyzero()
{
Finalvalue = 0;
}
public void division(int num1, int num2)
{
try
{
Finalvalue = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{ 
Console.WriteLine("Result: {0}", Finalvalue);
 }
}
static void Main(string[] args)
{
Divbyzero d = new Divbyzero();
d.division(25, 0);
Console.ReadKey();
}
}
}

In the above program, we have a class which contains a method to divide two integers. In integer arithmetic division by zero is not allowed. In this program, whenever a division by zero is done, the DivideByZeroException is thrown. The code inside the catch block is executed followed by the code in finally block. This way the DivideByZeroException is handled by this program.

If you’re new to C# programming, you may want to first take this tutorial to learn how to write your own C# programs.

Exception Classes in C#

In C# all the exceptions are represented by a class. All the exception classes are derived directly or indirectly from the System.Exception class.

  • System.IO.IOException – This class handles I/O exceptions.
  • System.IndexOutOfRangeException– This class handles exceptions which are thrown when a function refers to an array index out of range.
  • System.ArrayTypeMismatchException– Here exceptions raised when incorrect type matching with the array are handled.
  • System.NullReferenceException– Exceptions generated from deferencing a null object is handled by this class.
  • System.DivideByZeroException– Exception raised when division by zero occurs are handled by this class.
  • System.InvalidCastException-Exceptions during type casting are handled by this class.
  • System.OutOfMemoryException– This class handles exception raised because of insufficient free memory.
  • System.StackOverflowException-This class handles exceptions generated from stack overflow.

Explore more about exception classes in C# with this course.

Example 2: Program that Handles ArgumentException and ArgumentNullException Types

using System;
class Example
{
static void Main()
{
try
{
New_method(null);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
try 
{
New_method("");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine(New_method("test"));
}
static int New_method(string argument)
{
if (argument == null)
{
throw new ArgumentNullException("argument");
}
if (argument.Length == 0)
{
throw new ArgumentException("Zero-length string invalid", "argument");
}
return argument.Length;
}
}

In this program, a method is called. If null is passed as an argument then the ArgumentNullException is thrown. In case the length of the argument is zero, then the ArgumentException is thrown with the appropriate message. Learn more about handling various exceptions in C# with this course.

Example 3: Program that Throws Array Mismatch Exception

class Example
{
static void Main()
{
string[] array1 = { "monkey", "lion", "zebra" };
object[] array2 = array1;
array2[0] = 7;
}
}

Here when an array element location is assigned to an object whose type is not compatible the ArrayTypeMismatchException is thrown. Note that whenever an array element is assigned to an object of invalid type this exception is invariably thrown.

Example 4: Program to Explain FileNotFoundException

using System;
using System.IO;
class Example
{
static void Main()
{
try
{
using (StreamReader reader = new StreamReader("testfile.txt"))
{
reader.ReadToEnd();
}
}
catch (FileNotFoundException e)
{
Console.WriteLine(e);
}
}
}

In this program, when an attempt is made to read a non-existing file, we throw an exception.

Example 5: Program that Generates Out-of-Memory Exception

class Example
{
static void Main()
{
string value = new string('x’, int.MaxValue);
}
}

Since an attempt is made to create a string of 2 giga bytes, OutOfMemoryException is raised. This particular exception is thrown by the .NET Framework execution engine. Note that it may occur during any allocation call at runtime.

Example 6: Program to Generate TypeInitializationException

using System;
class Example
{
static Newmethod()
{
int num = 30;
int denominator = int.Parse("0");
int newvalue = num / denominator;
Console.WriteLine(result);
}
static void Main()
{
}
}

During runtime, the integer variable num is assigned the value of an integer which is divided by a non-integer value. Since, there is a mismatch during the initialization, the TypeInitializationException is thrown.

Example 7: Program that Handles IOException

using System;
using System.IO;
class Example
{
static void Main()
{
try
{
File.Open("C:\\unique.txt", FileMode.Open);
}
catch (IOException)
{
Console.WriteLine("IO Exception occurred. Please check your file");
}
}
}

Here we have a simple function to catch the IO Exception, in which we just print out the cause.

Example 8: Program that Handles FileNotFoundException

Here if for any reason the file cannot be opened, an IOException is thrown. Note that if IOException is caught, it is not required to detect other file handling exceptions if they occur.

using System;
using System.IO;
class Example
{
static void Main()
{
try
{
File.Open("C:\\unique.txt", FileMode.Open);
}
catch (FileNotFoundException)
{
Console.WriteLine(" File Not found");
}
catch (IOException)
{
Console.WriteLine("IO");
}
}
}

Here we catch the possible FileNotFoundException with a separate catch block. Only if another file handling exception occurs, the IOException block is entered.

Example 9: Program that Causes OverflowException

class Example
{
static void Main()
{
new_method
{
int newvalue = int.MaxValue + int.Parse("1");
}
}
}

Here we assign an integer variable to one greater than the maximum value that can be stored in an integer. An OverflowException is thrown during runtime.

Example 10: Program that Causes DirectoryNotFoundException: C#

using System.IO;
class Example
{
static void Main()
{
Directory.GetDirectories("C:\\Sciencefiction\\");
}
}

In the above program, When the Directory.GetDirectories method is called on a directory that does not exist on the computer, the DirectoryNotFoundException  is thrown.

We hope that you found this tutorial interesting and useful. Programming is best learned by writing out the code yourself, and running it. We recommend that you experiment with the code given above as well as write your own programs. Note that this is just one aspect of C#. To get a more holistic perspective about C# programming we recommend you take this course.