Introduction
The exceptions are anomalies that occur during the execution of a program.Exception handling is a mechanism in .NET framework to detect and handle run time errors. They can be because of user, logic or system errors. If a user (programmer) does not provide a mechanism to handle these anomalies, the .NET runtime environment provides a default mechanism, which terminates the program execution.
In C# there are three keywords Try, Catch and Finally for handling exceptions.
In try block statements it might throw an exception whereas catch handles that caused by try block if one exists.
The finally block is used for doing any clean up process. The statement in finally block always executes.
e.g.
try
{
// this can cause an exception.
}
catch (Type x)
{
// for handling the exception.
}
finally
{
//this will execute.
}
Exception Class
Following are some common exception classes.
SystemException- This exception means a failed run-time check used as a base class for other.
AccessException- This exception means failure to access a type member, such as a method or field.
ArithmeticException- This exception means arithmetic over – or underflow has occurred.
DivideByZeroException- This exception means an attempt was made to divide by zero.
FormatException- This exception means the format of an argument is wrong.
IndexOutOfRangeException- This exception means an array index is out of bounds.
NotSupportedException- This exception indicates that a method is not implemented by a class.
NullReferenceException- This exception means attempt to use an unassigned reference.
OutOfMemoryException- This exception means not enough memory to continue execution.
StackOverflowException- This exception means a stack has overflow.
Custom Exception
- Although the .NET framework contains all kinds of exception types which are sufficient in most cases, it can make sense to define custom exceptions in your own applications. They can greatly simplify and improve the error handling and thus increase the overall code quality. Generally, for large scale projects (i.e. having multiple modules talks to each other), one should define custom exceptions.
- For Implementing Custom Exception Handling, we need to derive the class CustomException from the system Base Class ApplicationException.
- Any Custom Exception you create needs to derive from the System.Exception class. You can either derive directly from it or use an intermediate exception like SystemException or ApplicationException as base class.
According to the .NET framework documentation, SystemException is meant only for those exceptions defined by the common language runtime whereas ApplicationException is intended to be used by user code. An "ApplicationException is thrown by a user program, not by the common language runtime. If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception, but does not add new functionality. This exception is provided as means to differentiate between exceptions defined by applications versus exceptions defined by the system."
Steps to Create Custom Exception
- Implement error handling in the user interface.
- Create and implement custom error messages.
- Create and implement custom error handlers.
- Raise and handle errors.
Illustrates a Custom Exception
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication2
{
class MyException :ApplicationException
{
public void MyExceptiona()
{
MessageBox.Show("An exception occured");
}
public void MyDivideException()
{
MessageBox.Show("Exception occured, divisor should not be zero");
}
}
class TestMyException
{
public static void Main(String[] arg)
{
int d, div, res;
div = Int32.Parse(Console.ReadLine());
d = Int32.Parse(Console.ReadLine());
try
{
if (div == 0)
{
throw new MyException();
}
}
catch (MyException e)
{
e.MyDivideException();
}
res = d / div;
Console.WriteLine("Result:{0}", res);
}
}
}
Output
When we enter the first value as 0 and second value as 9, it will show an Error message Box as shown in the following figure:
Here we have created our own custom exception MyDivideException() which when generated, shows an Error message box as "Exception occured, divisor should not be zero"
Catching and handling the custom exception
try
{
if (div == 0)
{
throw new MyException();
}
}
catch (MyException e)
{
e.MyDivideException();
}
res = d / div;
Console.WriteLine("Result:{0}", res);
}
Here in the try block statements it might throw an exception whereas catch block handles that caused by the try block if one exists.
Resources
Here are some useful related resources:
Custom Exception Handling in C#
Best Practices of Exception Management
Exception Handling in C#
Exception Handling and .NET
Guide to Improving Code Performance in .NET: Part II