Exception Handling in C#
Last Updated :
15 Sep, 2021
An exception is defined as an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of occurrence of an exception is not known to the program. In such a case, we create an exception object and call the exception handler code. The execution of an exception handler so that the program code does not crash is called exception handling. Exception handling is important because it gracefully handles an unwanted event, an exception so that the program code still makes sense to the user.
Keyword |
Definition |
try |
Used to define a try block. This block holds the code that may throw an exception. |
catch |
Used to define a catch block. This block catches the exception thrown by the try block. |
finally |
Used to define the finally block. This block holds the default code. |
throw |
Used to throw an exception manually. |
Let us take a simple example to understand what an exception is:
csharp
using System;
class GFG {
static void Main( string [] args)
{
int [] arr = { 1, 2, 3, 4, 5 };
for ( int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
Console.WriteLine(arr[7]);
}
}
|
Runtime Error:
Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at GFG.Main (System.String[] args) [0x0002e] in <9fa39b3b4dec49eb8af89dc70d5a0618>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at GFG.Main (System.String[] args) [0x0002e] in <9fa39b3b4dec49eb8af89dc70d5a0618>:0
Output:
1
2
3
4
5
In the code given above, the array named ‘arr’ is defined for 5 elements, indices 0 to 4. When we try to access the 7th element of the array, that is non-existent, program code throws an exception and the above message is displayed. The exception can be handled using the System.Exception class of C#. This will be depicted in the code given below.
Exception Handling Using try-catch block
The code given below shows how we can handle exceptions using the try-catch block. The code that may generate an exception is placed inside the try block. In this case, the access to the 7th element is put inside the try block. When that statement is executed an exception is generated, which is caught by the catch block. The object of the type IndexOutOfRangeException is used to display a message to the user about the exception that has occurred.
Syntax:
try
{
// statements that may cause an exception
}
catch( Exception obj)
{
// handler code
}
csharp
using System;
class Program : System.Exception {
static void Main( string [] args)
{
int [] arr = { 1, 2, 3, 4, 5 };
for ( int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
try {
Console.WriteLine(arr[7]);
}
catch (IndexOutOfRangeException e) {
Console.WriteLine( "An Exception has occurred : {0}" , e.Message);
}
}
}
|
Output:
1
2
3
4
5
An Exception has occurred : Index was outside the bounds of the array.
Using Multiple try-catch blocks
In the code given below, we attempt to generate an exception in the try block and catch it in one of the multiple catch blocks. Multiple catch blocks are used when we are not sure about the exception type that may be generated, so we write different blocks to tackle any type of exception that is encountered.
The finally block is the part of the code that has to be executed irrespective of if the exception was generated or not. In the program given below the elements of the array are displayed in the finally block.
Syntax:
try
{
// statements that may cause an exception
}
catch(Specific_Exception_type obj)
{
// handler code
}
catch(Specific_Exception_type obj)
{
// handler code
}
.
.
.
finally
{
//default code
}
csharp
using System;
class Program {
static void Main( string [] args)
{
int [] arr = {19, 0, 75, 52};
try {
for ( int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i] / arr[i + 1]);
}
}
catch (IndexOutOfRangeException e) {
Console.WriteLine( "An Exception has occurred : {0}" , e.Message);
}
catch (DivideByZeroException e) {
Console.WriteLine( "An Exception has occurred : {0}" , e.Message);
}
catch (ArgumentOutOfRangeException e) {
Console.WriteLine( "An Exception has occurred : {0}" , e.Message);
}
finally {
for ( int i = 0; i < arr.Length; i++) {
Console.Write( " {0}" , arr[i]);
}
}
}
}
|
Output:
An Exception has occurred : Attempted to divide by zero.
19 0 75 52
User Defined Exceptions
User-defined exceptions are useful when we want to code an exception that may not be defined by the language. For example, in a boiler room, if the temperature rises above some threshold then the heat must be turned off. For understanding how user-defined exceptions are used we take an example of a division by zero. Here we define a class DivByZero that inherits from Exception and is called by the DivisionOperation function when the denominator is equal to zero. Since the call for the function is may or may not throw an exception it is placed in the try block. A catch block is defined to catch any exception of type Exception and the Message property prints the type of exception that has occurred.
csharp
using System;
class DivByZero : Exception {
public DivByZero()
{
Console.Write( "Exception has occurred : " );
}
}
class Program {
public double DivisionOperation( double numerator,
double denominator)
{
if (denominator == 0)
throw new DivByZero();
return numerator / denominator;
}
static void Main( string [] args)
{
Program obj = new Program();
double num = 9, den = 0, quotient;
try {
quotient = obj.DivisionOperation(num, den);
Console.WriteLine( "Quotient = {0}" , quotient);
}
catch (Exception e) {
Console.Write(e.Message);
}
}
}
|
Output:
Exception has occurred : Exception of type 'DivByZero' was thrown.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...