C# Part 10: Exception Handling in C#
Please Subscribe Youtube| Like Facebook | Follow Twitter
Exception Handling in C#
In this article, we will provide a detailed overview of Exception Handling In C# and provide examples of how they are used in C# programming.
Exception handling is a crucial aspect of programming in C#. It allows developers to gracefully handle and recover from runtime errors, ensuring the stability and reliability of their applications. This article explores the fundamentals of exception handling in C#, along with example.
In C#, exceptions are objects that represent abnormal conditions or errors that occur during program execution. They disrupt the normal flow of the program and need to be handled appropriately. Exceptions can occur due to various reasons, such as invalid input, file system errors, network issues, or unexpected behavior.
Exception Handling syntax C#
In C#, exception handling is accomplished using the try, catch, finally, and throw keywords. Here is the syntax for exception handling in C#:
try
{
// Code that may raise an exception
}
catch (ExceptionType1 exceptionVariable1)
{
// Code to handle ExceptionType1
}
catch (ExceptionType2 exceptionVariable2)
{
// Code to handle ExceptionType2
}
catch (ExceptionType3 exceptionVariable3)
{
// Code to handle ExceptionType3
}
// Optionally, you can have more catch blocks for different exception types
finally
{
// Code that will always execute, regardless of whether an exception occurred or not
}
Let’s break down the syntax:
The try block contains the code that may throw an exception. It is enclosed within the try keyword.
If an exception occurs within the try block, the runtime will immediately transfer control to the appropriate catch block based on the type of the exception.
Each catch block specifies the type of exception it can handle using the ExceptionType parameter. When an exception of that type occurs, the corresponding catch block is executed. The exception object is assigned to the specified exceptionVariable within the catch block, allowing you to access information about the exception.
You can have multiple catch blocks to handle different types of exceptions. They are evaluated sequentially, and the first matching catch block is executed.
The finally block is optional and follows the catch blocks. It contains code that will always execute, regardless of whether an exception occurred or not. It is typically used for cleanup tasks or releasing resources.
Optionally, you can use the throw statement to explicitly throw an exception. This can be useful when you want to propagate an exception to a higher level or create custom exception handling scenarios.
Example
Here’s a simple example to illustrate the syntax:
// Online C# Editor for free
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int result = a / b;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Generic Error: " + ex.Message);
}
finally
{
Console.WriteLine("Finally block executed.");
}
}
}
Output
Error: Attempted to divide by zero. Finally block executed.
In the above example, if a DivideByZeroException occurs during the division operation, the control will be transferred to the first catch block. If any other exception occurs, it will be caught by the second catch block. Regardless of the exception, the finally block will always execute, printing “Finally block executed.”
Rethrow an Exception in C#
Here’s an example that demonstrates how to rethrow an exception in C#:
using System;
class Program
{
static void Main()
{
try
{
DivideNumbers(10, 0);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
Console.WriteLine("Program execution continues...");
Console.ReadLine();
}
static void DivideNumbers(int a, int b)
{
try
{
int result = a / b;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero.");
// Rethrow the exception
throw;
}
}
}
Output
Cannot divide by zero. An error occurred: Attempted to divide by zero. Program execution continues...
In this example, the DivideNumbers method attempts to divide two numbers a and b. If a DivideByZeroException occurs, it is caught in the catch block. The catch block displays an error message and then rethrows the exception using throw.
The Main method calls the DivideNumbers method with arguments 10 and 0, which will trigger a DivideByZeroException. The exception is caught in the catch block in the Main method, and an error message is displayed.
As you can see, the exception is rethrown in the DivideNumbers method, caught in the Main method, and then displayed with an additional error message. The program execution continues after the exception handling block, allowing further code execution.
Rethrowing exceptions can be useful when you want to handle exceptions at different levels of your application or when you need to provide additional context or logging information as the exception propagates.
Conclusion
In conclusion, exception handling is a critical aspect of writing robust and reliable code in C#. By effectively handling exceptions, you can ensure the stability and reliability of your applications, improve error reporting and debugging, and enhance the overall user experience.
C# Beginner Tutorial Series
- C# Part 1: Setup and Introduction
- C# PART 2: UNDERSTANDING BASIC DATA TYPES AND VARIABLES IN C#
- C# PART 3: OPERATORS AND EXPRESSIONS IN C#
- C# PART 4: CONTROL FLOW STATEMENTS IN C#
- C# Part 5: Methods In C#
- C# Part 6: Arrays In C#
- C# Part 7: String Manipulation In C#
- C# Part 8: Object-Oriented Programming In C# (Classes and Objects)
- C# Part 9: Object-oriented Programming In C# (OOP Pillars)
- C# Part 10: Exception Handling in C#