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);
}
}
}
You can see an error in the below image. if you print the value out of index
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.
Course Video:
Course Video In English:
Exception handling in C# is a process to handle runtime errors in a controlled and structured manner using try-catch blocks.
It ensures that the application continues running smoothly by catching and resolving errors during runtime.
- try: Defines a block of code to monitor for exceptions.
- catch: Handles the exception.
- finally: Executes code after try and catch, regardless of whether an exception occurred.
- throw: Used to throw an exception.
Yes, multiple catch blocks can handle different types of exceptions.
The finally block is used to execute code regardless of whether an exception occurs, typically for cleanup operations.
- throw: Preserves the original stack trace.
- throw ex: Resets the stack trace, making it harder to trace the original error.
- Avoid using exceptions for regular control flow.
- Catch specific exceptions rather than generic ones.
- Always clean up resources using finally or a using statement.
The StackTrace property provides details about the sequence of method calls that led to the exception.
Yes, exceptions can be rethrown using the throw keyword in a catch block to propagate them further.
C# provides several types of exceptions, some of the most common ones include:
- System.Exception: The base class for all exceptions.
- System.NullReferenceException: Thrown when an object reference is not set to an instance of an object.
- System.DivideByZeroException: Thrown when attempting to divide by zero.
- System.IndexOutOfRangeException: Thrown when trying to access an array element outside its bounds.
- System.IO.IOException: Thrown when an I/O error occurs.
Each of these exceptions can be caught and handled in the appropriate catch block.
Iqra Technology Academy offers free video tutorials in Hindi on exception handling in C#. These tutorials cover the basic concepts of exception handling, types of exceptions, and practical examples using the try, catch, finally, and throw keywords. The tutorials are designed to help you understand how to manage errors effectively in your C# applications.
Iqra Technology Academy offers a free online course in Hindi that covers exception handling in C#. The course explains the types of exceptions, how to handle them using different techniques like try-catch, and how to implement custom exceptions. You will learn practical techniques for managing errors and improving the stability of your C# applications.