C# .Net Tutorial Exceptions


This article is a basic c# tutorial dealing with exceptions in c# .net.

Practically any program including c# .net can have some amount of errors. They can be broadly classified as compile-time errors and runtime errors. Compile-time errors are errors that can be found during compilation process of source code. Most of them are syntax errors. Runtime errors happen when program is running.

It is very difficult to find and debug the run-time errors. These errors also called exceptions. Rules of good coding style say that program must be able to handle any runtime error. Exception generates an exception call at runtime. Exceptions in C# can be called using two methods:

  1. Using the throw operator. It call the manage code anyway and process an exception.
  2. If using the operators goes awry, it can generate an exception.

Simple Exceptions – .Net C# Tutorial:

C# language uses many types of exceptions, which are defined in special classes. All of them are inherited from base class named System.Exception. There are classes that process many kinds of exceptions: out of memory exception, stack overflow exception, null reference exception, index out of range exception, invalid cast exception, arithmetic exception etc. This c# tutorial deals with DivideByZero c# exception and custom classes in c# exceptions.

C# has defined some keywords for processing exceptions. The most important are try, catch and finally.

The first one to be known is the try operator. This is used in a part of code, where there exists a possibility of exception to be thrown. But operator ?try? is always used with the operators: catch and finally.

See the following example of handling a simple exception in c#.


//Sample code for C# Exception tutorial using try , catch

// try catch exception
int zero = 0;
try
{
int div = 100/zero;
}
catch(DivideByZeroException)
{
Console.WriteLine("Division by zero exception passed");
}

This code in runtime throws a DivideByZeroException and writes some message through the console. But if you want to release some resources that were created you must use try ? finally construction. Finally will be called even if there were no exceptions raised.


//Sample code for C# Exception tutorial using try, finally
Bitmap bit = null;
// try finally exception
try
{
    bit = new Bitmap(100,100);
}
finally
{
	bit.Dispose();
Console.WriteLine("bitmap is disposed");
}

In the similar way we can use try ? catch ? finally construction. The attached c# tutorial program contains sample including all the three.

Custom Exception Classes – C# Tutorial:

Some larger projects might have a requirement of creating their own custom exception classes. Let us try to create class that validates email address. It will validate for the ?@? symbol. Please have a look on the following piece of code:


//Sample code for C# .Net Exception tutorial - validates an email address
public class TextException : Exception
{
	public TextException() : base()<br>
	{
	}

	public TextException(string message) : base(message)
	{

	}
}

public class MailValidator
{
MailValidator()
{

}

private static char symbol = '@';

public static void TestEnteredMail(string mailAddress)
{
if(mailAddress.IndexOf(symbol)==-1)
{
	Console.WriteLine("The string entered is not a valid email address");<br>
throw(new TextException());
}
}
}

Here were created a C# .Net TextException class that inherits from System.Exception class of .NET class library. Actually it does nothing, but there is an additional class MailValidator. It has TestEnteredMail method that raises a TextException. Now look at usage of it in Main function.


try
{
	MailValidator.TestEnteredMail(Console.ReadLine());
}
catch(TextException)
{
	Console.WriteLine("Exception was passed");
}

So, if user enters mail address without it throws an exception. All the sources are attached and compliable. The example can be compiled using .NET command line through the csc command line program. You only need to type csc filename.cs.