How to Create & Handle Error in C#


When writing a code in any programming language, a writer can come across two main types of errors, one is a syntax error and the other is a logical error or exception. A syntax error is mainly due to the programmer`s own mistake. This type of error occurs when a programmer unknowingly or knowingly, uses a wrong syntax for a command. Most of the times, your compiler will specify the error occurs when you are making a mistake in your logic or trying to attempt something impossible such as diving an integer by zero. The program will generally crash in such a case, unless you handle the exception.

In this tutorial, we will create an exception in our C# code to demonstrate how a logical error or an exception occurs. Furthermore, we will also try to demonstrate a basic method for handling such exceptions.

  • Begin with creating a New Project from File Menu or shortcut keys Ctrl+Shift+N in Microsoft Visual Studio 2010. Now to learn to handle an error, we will create an error by creating a program that divides any integer by zero. Initialize two integers x and y in your code. Assign any random integer value to x and assign 0 to y. And now try to divide x by z. You will write the code like this.


namespace TutsCode
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 1;

            int y = 0;

            double z = x / y;

        }
    }

}




















  • At this moment, your program should appear like this.


Console Application in Csharp


There will be no syntax error in this program at this point. However, when you run this program, it will crash because dividing any integer by 0 is not possible.


  • When you run this program, the following error will appear on your screen:
DivideByZeroException Csharp


As explained earlier, you cannot divide a program and so your program just crashed and died. You can see in your Local & Call Stack tabs on Visual Studios about the error details. Now that you have created an error, the next step is to figure out how to handle this error or exception.

  • Now to avoid this situation that we have created in our program and keeping it from crashing, we will surround the certain area of a code, which we used to generate an error, in a Try block. To do this, selection the lines that you want to surround using mouse selection and press right click on your mouse. From the drop down menu, select the option ‘Surround With’, and from the following menu, choose ‘Try’. If you follow all the steps correctly, your program should look like this at the moment.

try & catch in Csharp


As you can see, the program will automatically add a new Catch block to your code.

  • Now the next step is to write the code in Catch block, to try the handle the exception. First of all, we will give a name to Exception class. We name it Error here to make clear what it does.  Now inside the block we will write the following line of code: 

catch (Exception error)
{
    Console.WriteLine(error.Message);

}











The code we have written so far means that commands written inside the Try block will try to execute. However, if something bad happens while execution of the Try block, the program is going to catch that exception. When an error is caught, the program will respond to that error according to the code written inside the Catch block. At this point your program should appear like this:


catch exception error in Csharp


  • Now the command we wrote inside the Catch block i.e. ‘Console.WriteLine(error.Message)‘ is going to handle the exception that occurs. The exception class is pretty big, so error has a bunch of properties.  You can various options like Stack Trace, Inner Exceptions, but for our basic code to handle error, we will stick with the Message option.  
  • As we know the purpose here is to understand, what happened that caused an exception. Therefore, we will include another line in the body of Catch block. 
Console.Read();






This command will read the error message and make it appear on screen when we run the program. Now our code in the Catch block should look like this:

  catch (Exception error)
  {
      Console.WriteLine(error.Message);
      Console.Read();

  }












After adding these lines, when we run this program, the following message will appear:

Execute Console Application

It shows that the code we wrote runs anything that is written in Try block. If an error is occurs, it catches the error and displays the error on screen.

  • However, there is a small problem with that code that we have written so far. It is like an if/else statement. Try block is executed, and if an error occurs then Catch block will be executed and it will read the error message. However, we will see no results if there is no error found, as the Catch block only runs if an error is occurred. Now to make sure that are able to read the message even if there is no error, we will create a new block here, by the name Finally. We will cut the Read command from Catch block and paste it in Finally block. Our code should appear like this now:

 catch (Exception error)
 {
    Console.WriteLine(error.Message);
 }
 finally
 {
    Console.Read();

 }

  • Now in this last phase of our tutorial, we will choose a different path to see what happens if we want to intentionally throw an exception in our program. We will use a simple “Hello World” code and put an exception in it.

To do this, we will replace the code in Try block with the following code:
Console.WriteLine("Hello World");
Console.WriteLine("GoodBye");
However, we are aiming to intentionally raise an error. Therefore we will include another line in this block for the error condition to exist. For that we will use Throw keyword. Using this command, we will create a new exception, inside the try block. Now under normal circumstances, the above code will run without any exception and you will see both “Hello world” and “GoodBye” statements appear on your screen. However, we have altered the code to something like this:
Console.WriteLine("Hello World");
throw new Exception("good Bye Cruel World");
Console.WriteLine("GoodBye");






Now what happens when you run this code is that after displaying “Hello World” on screen, when the program reaches the throw keyword, the program will instantly go down in to the Catch condition. Now if you run the program, your output will appear like this:

How to Create & Handle Error in Csharp


Therefore, we can clearly see that if we do not want a certain part of our code to execute, we can use the throw keyword to put an exception in your program. The program will be automatically thrown in to the Catch condition in such a case. However, to make sure that our program does not crash we must have a Catch block written in our code. If we do not have a catch block, our program will crash.

By using these simple commands, you can simply generate and handle exceptions in your program. 

If you need any help feel free to leave a comment (or) contact me.

No comments:

Post a Comment