C# .Net Exceptions
C# .Net Exceptions
C# .Net Exceptions
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.
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.
}
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:
MailValidator()
{
if(mailAddress.IndexOf(symbol)==-1)
{
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)
{
}
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.