C# Exception

In our previous articles we discussed interfaces and in this post, we are going to discuss exception handling. Exceptions are everywhere, whenever code finds something broken it raises an exception. So in this post, we will learn about exceptions, when they are raised and how to handle them in our application.


C# Exception Handling
Exception Handling In C# 





What Is An Exception?

In the context of C#, whenever a run-time error occurs, the .Net Framework breaks the execution of code and raises an Exception. This raised exception contains all the information about the error. Like at which line of code the error occurred, which method was executing that code and other useful information. .Net raises the Exception as an object of System.Exception class.

What Is System.Exception Class?

Exception class is the base class for all types of exceptions that .Net framework raises. Shown below is the list of specific exceptions that .Net framework can raise:


C# Exception Types



Now all these exceptions are raised by the framework when specific errors have occurred during runtime. Each of these specific exceptions has a class present with the same name. Now if you go and see these exception classes, you will see that all these classes are inheriting from common class System.SystemException which is actually inheriting from System.Exception class. This means that Exception class is providing all the basic properties and methods for these derived above exception classes. Why we need these classes, we will discuss this shortly.

This System.Exception class provides information using some properties, I am pointing out some of those:

Data: It is a Dictionary object and returns all the key/value pair of information if we have explicitly provided to an exception.

InnerException: Gets the Exception instance that caused the current exception. Helpful when one exception is raised by another exception.

Message: Returns a concise description of the error occurred. 

Source: Gets or sets the name of the application or the object that causes the error.

StackTrace: This returns a string containing all the call stack from where the code was called and at which line of code the exception was raised.

TargetSite: Gets the method in which the current exception was raised.

Exception Handling in C#

Now as we know that if any error occurs at runtime, an exception is raised. What to do with that exception?
If we don't do anything about it, the Exception would reach to the end user. For windows application, the EXE would stop working and for web application user will see a broken error page saying unhandled exception occurred.

So to prevent this, we must handle the exception. For this .Net has the concept of try-catch blocks. It appears something like this shown below:



try
{
   //code goes here
}
catch (Exception ex)
{
    //exception handling code goes here
}

Now using these try catch block we can handle any error occurred in our application. The only requirement is that the catch block will only catch the exceptions occurred in the code written in a try block. Now using these try-catch blocks we can catch an exception and handle it the way we want.

There can be many ways of handling an exception. Consider the below example:


public void Divide(int a, int b)
{
 try
 {
  float result = 0;
  result = a / b;
  Console.WriteLine(result);
 }
 catch (DivideByZeroException ex)
 {
  Console.WriteLine("The divisor should not be zero");
 }
 catch (Exception ex)
 {
  //ex variable contains object of Exception being raised
  //Code to save error in DB or Log Files
 }
}

In above example, there's method as Divide. Now in this method exception handling is being done. If any line of code in try block causes an error, it will be trapped inside the catch blocks. Now the main thing to notice in this code is that we have used two catch blocks.
One catch block is for DivideByZeroException and another catch block is for any other exception. So we can handle specific exceptions (shown in starting of this post) as per our needs and show a custom message to the end user to optimize the user's experience.

Now we can have as many catch blocks as we want and we have ex variable available for use. We can either log the information from this ex variable to DB or we can show a custom message to the user and suppress this error.

**You can also throw an error if you want using 'throw new Exception();' and provide all the necessary information. This is helpful in case the response from Services is not proper and you want to handle that situation as exceptions.

Finally In Try-Catch blocks

We now know about try and catch blocks, but there's another block which is called finally block. The purpose of this block is to execute lines of code which we want to be executed in any case, even if an exception has occurred in a try block. The code inside the finally block is always executed. The best example of this finally block is when we open a SQL server connection inside a try block and close it inside the finally block so that the connection is properly closed even after the error. Consider the below syntax for finally block, it has to be placed after the catch block


public void Divide(int a, int b)
{
 try
 {
  float result = 0;
  result = a / b;
  Console.WriteLine(result);
 }
 catch (DivideByZeroException ex)
 {
  Console.WriteLine("The divisor should not be zero.");
 }
 catch (Exception ex)
 {
  //ex variable contains object of Exception being raised
  //Code to save error in DB or Log Files
 }
        finally
        {
            Console.WriteLine("This message will always be printed.");
        }
}

Now in the above example, if Divide method is called with parameters a=10 & b=0 then DivideByZeroException would be raised. This means that the first catch block would be called and right after it the finally block would be called. So, the out would be

The divisor should not be zero.
This message will always be printed.

The second catch block is only executed when the exception raised is not listed in any other catch block. Because the second catch block has Exception class and it is the base class of all the exceptions.

So, that's all about Exceptions in C# and how do we handle them.

Watch below a small helful video for Exception Handling In C#:


Let us know your queries. We are happy to help.

Happy Learning!! Follow our full C# Tutorial Index for complete series.



Comments

Popular posts from this blog

Just Maths - Views, View Groups and Layouts

Create Dynamic Table In JavaScript Using WebMethod And jQuery AJAX Without Postback