All the ways of Exception Handling in C#
Exception handling is a crucial aspect of writing robust and reliable code in any programming language.
In C#, the .NET framework provides a powerful and flexible mechanism for handling exceptions.
In this blog, we’ll explore various techniques for exception handling in C# with code snippets to illustrate each approach.
Embark on a journey of continuous learning and exploration with DotNet-FullStack-Dev. https://dotnet-fullstack-dev.blogspot.com/
Basics of Exception Handling
In C#, exceptions are objects that represent errors during program execution.
When an error occurs, an exception is thrown, and the program looks for an appropriate exception handler to catch and handle the exception.
The try
, catch
, finally
, and throw
keywords are fundamental to C# exception handling.
1. Basic Try-Catch Block
The simplest form of exception handling involves using a try
block to enclose the code that might throw an exception and a catch
block to handle the exception.
try
{
// Code that may throw an exception
int result = 10 / int.Parse(Console.ReadLine());
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: Division by zero");
}
catch (FormatException ex)
{
Console.WriteLine("Error: Invalid input format");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
In the above example, if a DivideByZeroException
or a FormatException
occurs, the corresponding catch
block is executed.
The last catch
block with Exception
as its parameter is a generic handler that can catch any exception.
2. Multiple Catch Blocks
C# allows you to catch multiple exceptions in a single catch
block, providing a more concise way to handle different exception types.
try
{
// Code that may throw an exception
int result = 10 / int.Parse(Console.ReadLine());
}
catch (DivideByZeroException | FormatException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
Here, the catch
block handles both DivideByZeroException
and FormatException
using the |
(or) operator.
3. Finally Block
The finally
block is used to specify code that should always be executed, whether an exception is thrown or not. It is typically used for cleanup operations.
try
{
// Code that may throw an exception
int result = 10 / int.Parse(Console.ReadLine());
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: Division by zero");
}
catch (FormatException ex)
{
Console.WriteLine("Error: Invalid input format");
}
finally
{
Console.WriteLine("This block always executes, regardless of exceptions");
}
In this example, the finally
block is executed no matter what happens in the try
block.
4. Throwing Exceptions
You can explicitly throw exceptions using the throw
keyword. This is useful for custom exception handling scenarios.
try
{
int age = int.Parse(Console.ReadLine());
if (age < 0)
{
throw new ArgumentException("Age cannot be negative");
}
}
catch (ArgumentException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
In this case, an ArgumentException
is thrown if the entered age is negative.
5. Custom Exceptions
Creating custom exception classes allows you to provide more specific information about errors in your application.
public class CustomException : Exception
{
public CustomException(string message) : base(message)
{
}
}
try
{
// Code that may throw a custom exception
throw new CustomException("This is a custom exception");
}
catch (CustomException ex)
{
Console.WriteLine($"Custom Exception: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
Here, we’ve defined a CustomException
class that inherits from the Exception
class.
Conclusion
Exception handling is an essential aspect of writing robust and reliable C# code.
By using the try
, catch
, finally
, and throw
keywords, along with various techniques like multiple catch blocks and custom exceptions, you can create code that gracefully handles errors and provides meaningful feedback to users.
Understanding and implementing these techniques will contribute to the overall stability and maintainability of your C# applications.