Exception Handling in C#
In programming, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. It usually signals that something has gone wrong, such as trying to divide by zero, accessing an array out of its bounds, or opening a file that doesn’t exist.
Why Use Exception Handling?
Exception handling allows your program to deal with unexpected situations (exceptions) gracefully, without crashing. This makes your programs more robust and user-friendly.
The try/catch Block
In C#, exceptions are handled using try and catch blocks. Here’s a simple structure:
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
// Code that runs if an exception occurs
}
- The code that might throw an exception goes inside the try
- The catch block contains the code that runs if an exception is thrown. The Exception ex part allows you to capture information about the exception.
Example
using System;
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine(“Enter the first number: “);
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“Enter the second number: “);
int num2 = Convert.ToInt32(Console.ReadLine());
// Attempt to divide the numbers
int result = num1 / num2;
Console.WriteLine(“The result is: ” + result);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
You can see an error in the below image. if you divide 10 by 0. the system will give you an error
Explanation:
using System;
class Program
{
static void Main(string[] args)
{
try
Start of the try block to monitor for exceptions
Prompt the user to enter the first number
Console.WriteLine(“Enter the first number: “);
Read the user input, convert it to an integer, and store it in num1
int num1 = Convert.ToInt32(Console.ReadLine());
Prompt the user to enter the second number
Console.WriteLine(“Enter the second number: “);
Read the user input, convert it to an integer, and store it in num2
int num2 = Convert.ToInt32(Console.ReadLine());
Attempt to divide the first number by the second number
int result = num1 / num2;
Display the result of the division
Console.WriteLine(“The result is: ” + result);
}
catch (Exception ex)
Start of the catch block to handle any exceptions
Print the exception message to the console
Console.WriteLine(ex);
2. This example shows handling an IndexOutOfRangeException when accessing an array element that doesn’t exist.
using System;
class IndexOutOfBoundsExample
{
public static void Main()
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]);
}
catch (Exception ex)
{ Console.WriteLine(ex);
}
}
}
Explanation:
using System;
class IndexOutOfBoundsExample
Defines a class named IndexOutOfBoundsExample.
public static void Main()
The Main method is the entry point of the program.
try
Starts a try block to monitor for exceptions.
int[] numbers = { 1, 2, 3 };
Initializes an array named ‘numbers’ with three elements.
Console.WriteLine(numbers[5]);
Tries to access the sixth element (index 5) of the array, which doesn’t exist.
catch (Exception ex)
Catches any exception that occurs within the try block.
Console.WriteLine(ex);
Prints the exception details to the console.
3. This example handles a FormatException when trying to convert a non-numeric string to an integer.
using System;
class FormatExceptionExample
{
public static void Main()
{
try
{
string input = “abc”;
int number = int.Parse(input);
}
catch (FormatException ex)
{
Console.WriteLine(ex);
}
}
}
You can see error in below image
Explanation:
using System;
class FormatExceptionExample
Defines a class named FormatExceptionExample
public static void Main
The Main method is the entry point of the program.
try
Starts a try block to monitor for exceptions.
string input = “abc”;
Defines a string variable named ‘input’ with the value “abc”.
int number = int.Parse(input);
Tries to convert the string ‘input’ to an intege
catch (FormatException ex)
Catches any FormatException that occurs within the try block.
Console.WriteLine(ex);
Prints the exception details to the console.