Exception Handling in C#
Exception Handling in C#
Exception Handling is all about handling exceptions and is one of the most important topic in C#.
In this blog, I will explain about Exceptions and how to handle them using the different keywords we have in C# and finally, we will see some examples for the same.
Exception – What is it?
An exception can be termed as any error or an issue in our application code, which can change the execution flow to some different part of the program or might terminate the program itself.
All exceptions are defined inside a namespace System.Exception in C#. Some common exceptions include:
IndexOutOfRangeException, ArgumentOutOfRangeException, InvalidOperationException
C# also provides us with an option to create custom exceptions of our choice.
In order to avoid the program changing the execution flow or prevent its termination in an unexpected way, we go for handling of exceptions using Exception Handling mechanism in C#.
Exception Handling – How it is done ?
C# has provided us with some keywords to implement exception handling, which are try, catch finally and throw keywords.
try-catch are basically the application code blocks. By keeping the code inside try block, we make it code safe by verifying it since the catch block will catch the error occurred or raised based on the type of exception defined in the catch block.
Whenever some error occurs inside the code which is placed inside try block, the .NET runtime will check the catch block to find out if the exception type which is defined in the catch statement is of the same type of which the error is thrown or is a generic base class of exception which is being raised. Then, it will execute the catch block which matches with the type of the exception that is encountered.
We can add as many catch blocks for a single try block, but we should keep in mind that the specific catch block should come first followed by others and the generic catch block for base class of exception should come last.
It is not necessary that the catch block will execute, it might happen that no error or issue is encountered in the try block. Sometimes, we might need to do some kind of cleanup maybe of resources or close some database connections, for that we use finally block. The finally block is one which executes regardless of whether the exception has occurred or not.
Sometimes, there is a situation or scenario where we want to raise an exception, in that case we go for throw keyword.
Syntax:
Below is the syntax of exception handling in C#.
try
{
// application code
}
catch (Exception ex)
{
throw new Exception("Your Message", ex);
}
finally
{
// code for cleanup
}
Examples:
Let’s see some examples of handling exceptions in C#.
Example 1: DivideByZeroException
The below program will throw a DivideByZeroException if we divide a number by zero.
using System;
namespace ExceptionHandling {
class Numbers {
int result;
Numbers() {
result = 0;
}
public void division(int a, int b) {
try {
result = a / b;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args) {
Numbers d = new Numbers();
d.division(19, 0);
Console.ReadLine();
}
}
}
Example 2: FileException – FileNotFoundException / IOException
The below program will throw a FileNotFoundException if the requested file does not exist or IOException it the runtime is not able to read the requested file. This example makes use of multiple catch blocks for a single try block.
using System;
using System.IO;
namespace ExceptionHandling
{
public class ProcessFile
{
public static string ReadTheFile(string path)
{
var data = "";
try
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (var file = new StreamReader(stream))
{
data = file.ReadToEnd();
}
}
}
catch (FileNotFoundException ex)
{
data = "Could not find the file.";
}
catch (IOException ex)
{
data = "Not able to read the content from the file.";
}
catch (Exception ex)
{
data = "Some error occurred.";
}
return data;
}
}
}
