Understanding the try-catch blocks in C#

Using the try and catch block you can add intelligent exception handling to your code. In C# it is extremely simple to add exception handling using try and catch. But before you learn how to use them in your code let’s explain in brief about the functioning of try and catch blocks

Try block

If there is any code which you are writing and you expect it to throw an exception at runtime then you should put it inside the try block. If this code works properly then the program will run normally. But if it fails then the program will go to the catch block and execute the code written there.

Catch block

Try blocks cannot be used without a catch block. The code inside the catch block runs if the code inside the try block fails. If the code inside the try block does not fail then the code inside the catch block will never run.

Examples

Look at the code below

static void Main(string[] args)  {      try      {          Console.Write("Enter a number : ");          int i = Convert.ToInt16(Console.ReadLine());            // If input is correct then print this line          Console.WriteLine("Correct input received...");      }      catch      {          // If input is wrong then print this line          Console.WriteLine("Incorrect input received...");      }  }

Here we have a doubt that the user might not enter the correct integer input. Therefore we have written the code inside the try block. If the user enters the correct integer value from the keyboard then the output will be “Correct input received...” otherwise the program will throw an exception and the code inside the catch block will execute and print “Incorrect input received...”

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp