Home »
C#
Exception handling in C#
C# Exception Handling: Here, we are going to learn about the exception handling in C# with examples, here we will also see the various common exceptions and handling them using try catch block.
Submitted by IncludeHelp, on September 20, 2019
What an exception is?
An exception is a runtime error; that means an abnormal situation which is created at run time and the program doesn’t execute successfully. Due to the exceptions, our program gets crash.
There are following common exceptions are occurred during program:
- Divide by Zero
- File not found
- Array Index out of bound
- Null reference exception
- Invalid cast exception
- Arithmetic exception
- Overflow exception
- Out of memory exception etc.
Here is an example / program, that will generate exception
using System;
class Program
{
static void Main()
{
int number1 = 0;
int number2 = 0;
int result = 0;
Console.WriteLine("Enter Number : ");
number1 = int.Parse(Console.ReadLine());
result = number1 / number2;
Console.WriteLine("Result : " + result);
}
}
When we compile above program it does not produce any error. Compilation result will be like this,
------ Build started: Project: ConsoleApplication1, Configuration: Debug x86 ------
ConsoleApplication1 ->C:\Users\Arvind\Documents\Visual Studio 2010\Projects\ihelp\
ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
And, when we execute the program then it produces an exception like this, (in the program, we are trying to divide a number by 0).
The above program generates "Divide by Zero exception" and the program gets crashed. Because variable number1 is divided by number2 and output stored in the result variable. Where, the value of number2 is 0, thus, "divide by zero exception" occurred.
To handle such kind of exceptions, we use exception handling in C#.
try catch and finally blocks
Exception handling in C# can be handled using three blocks
- try
- catch
- finally
Syntax of exception handling blocks,
try
{
// code that can occur an exception
}
catch(Exception Type)
{
// code to handle the exception
// code to display the error message
}
finally
{
// code that should be executed
// whether exception is occurred or not
}
1) try block
In this block, we write the code that can produce an exception or runtime error. For example, in the previous program, there was an exception (divide by zero).
2) catch block
This block is executed when the code throws an exception that is written in a try block, catch block catches the exception and we can write the code to handle that exception or any message to display the exception as per user preference.
Here, we used the exception classes, there are the following exception classes used in C# to catch the exceptions.
- Exception
- DivideByZeroException
- NullReferenceException
- OutOfMemoryException
- InvalidCastException
- ArrayTypeMismatchException
- IndexOutOfRangeException
- AirthmeticException
- OverFlowExecption
These classes are available in System namespace. In the above classes, the Exception class is a superclass and others are sub-classes, The Exception class can catch any kind of exception thrown by the try block.
3) finally block
finally block is executed in all cases i.e. whether the program is generating an exception or not, before leaving the program, compiler moves to the finally block. This block can be used to write the codes that are compulsory for the execution of program like the closing of the file, releasing the memory, etc.
Here is the code (with exception handling) to handle divide by zero exception.
using System;
class Program
{
static void Main()
{
int number1 = 0;
int number2 = 0;
int result = 0;
try
{
Console.WriteLine("Enter Number : ");
number1 = int.Parse(Console.ReadLine());
result = number1 / number2;
Console.WriteLine("Result : " + result);
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Program exited normally");
}
}
}
Output