top
upGrad KnowledgeHut SkillFest Sale!

Search

C# Tutorial

handling is used to detect and handle these runtime errors. If there is no exception handling mechanism created by the programmer, then the default mechanism is used by the runtime environment. This terminates the program execution.Exception Handling KeywordsThe exception handling mechanism uses three main keywords i.e. try, catch and finally. Details about these are given as follows:1. tryIf the exception occurs inside the try block, the control is transferred to the required catch block. There may be multiple catch blocks after the try block.2. catchThe catch block handles the exception that has occured in an appropriate manner using exception handling mechanisms.3. finally The finally block executes some statements irrespective of whether an exception has occurred or not. If there is no exception in the try block, then control directly transfers to finally block and skips the catch block.The syntax of the try, catch and finally keywords in exception handling is given as follows:try {     // Statements that cause exception } catch (ExceptionType EName) {     // Statements that handle exception } finally {      // Remaining statements to be executed }In the above syntax, the try block contains the exceptions that may occur. There can be multiple catch blocks that handle the required exceptions. The finally block executes some remaining statements.A program that demonstrates exception handling is given as follows:Source Code: Program that demonstrates exception handling in C#using System; namespace ErrorHandlingDemo {   class Example   {      static void Main(string[] args)      {          int result = 0;          int a = 25;          int b = 0;          try         {            result = a / b;         }         catch (DivideByZeroException)         {            Console.WriteLine("Exception occured");         }         finally         {            Console.WriteLine("Result: {0}", result);         }      }   } }The output of the above program is as follows:Exception occured Result: 0Now let us understand the above program.The try block stores the result of a/b. If b is 0, then there is a DivideByZeroException and control goes to the catch block. In the catch block, it is printed that an exception has occurred. The finally block is executed if there is an exception or not. It prints the result of a/b. The code snippet for this is as follows:int result = 0;          int a = 25;          int b = 0;          try         {            result = a / b;         }         catch (DivideByZeroException)         {            Console.WriteLine("Exception occured");         }         finally         {            Console.WriteLine("Result: {0}", result);         }User Defined ExceptionsUser defined exceptions are custom exceptions that can be created by the users. This is done by inheriting the exception class.A program that demonstrates user defined exceptions is given as follows:Source Code: Program that demonstrates user defined exceptions in C#using System; namespace UserDefinedExceptionDemo {   class Example   {      static void Main(string[] args)      {         Age a = new Age();         try         {            a.displayAge();         }         catch(AgeIsNegativeException e)         {            Console.WriteLine("AgeIsNegativeException: {0}", e.Message);         }      }   } } public class AgeIsNegativeException: Exception {   public AgeIsNegativeException(string message): base(message)   {   } } public class Age {   int age = -5;   public void displayAge()   {      if(age < 0)      {         throw (new AgeIsNegativeException("Age cannot be negative"));      }      else      {         Console.WriteLine("Age is: {0}", age);      }   } }The output of the above program is as follows:AgeIsNegativeException: Age cannot be negativeNow let us understand the above program.The try and catch blocks are available in the Main() function. The displayAge() function is called in the try block. If the age is less than zero, then an exception message is printed in the catch block because the age cannot be less than zero. The code snippet for this is as follows: static void Main(string[] args)      {         Age a = new Age();         try         {            a.displayAge();         }         catch(AgeIsNegativeException e)         {            Console.WriteLine("AgeIsNegativeException: {0}", e.Message);         }      }The variable of type int is declared in class Age. The function displayAge() throws an exception if the age is less than zero. Otherwise, it prints the age. The code snippet for this is as follows:public class Age {   int age = -5;   public void displayAge()   {      if(age < 0)      {         throw (new AgeIsNegativeException("Age cannot be negative"));      }      else      {         Console.WriteLine("Age is: {0}", age);      }   } }
logo

C# Tutorial

Exception Handling in C#

handling is used to detect and handle these runtime errors. If there is no exception handling mechanism created by the programmer, then the default mechanism is used by the runtime environment. This terminates the program execution.

Exception Handling Keywords

The exception handling mechanism uses three main keywords i.e. try, catch and finally. Details about these are given as follows:

1. try

If the exception occurs inside the try block, the control is transferred to the required catch block. There may be multiple catch blocks after the try block.

2. catch

The catch block handles the exception that has occured in an appropriate manner using exception handling mechanisms.

3. finally 

The finally block executes some statements irrespective of whether an exception has occurred or not. If there is no exception in the try block, then control directly transfers to finally block and skips the catch block.

The syntax of the try, catch and finally keywords in exception handling is given as follows:

try
{
    // Statements that cause exception
}
catch (ExceptionType EName)
{
    // Statements that handle exception
}
finally
{
     // Remaining statements to be executed
}

In the above syntax, the try block contains the exceptions that may occur. There can be multiple catch blocks that handle the required exceptions. The finally block executes some remaining statements.

A program that demonstrates exception handling is given as follows:

Source Code: Program that demonstrates exception handling in C#

using System;
namespace ErrorHandlingDemo
{
  class Example
  {
     static void Main(string[] args)
     {
         int result = 0;
         int a = 25;
         int b = 0;
         try
        {
           result = a / b;
        }
        catch (DivideByZeroException)
        {
           Console.WriteLine("Exception occured");
        }
        finally
        {
           Console.WriteLine("Result: {0}", result);
        }
     }
  }
}

The output of the above program is as follows:

Exception occured
Result: 0

Now let us understand the above program.

The try block stores the result of a/b. If b is 0, then there is a DivideByZeroException and control goes to the catch block. In the catch block, it is printed that an exception has occurred. The finally block is executed if there is an exception or not. It prints the result of a/b. The code snippet for this is as follows:

int result = 0;
         int a = 25;
         int b = 0;
         try
        {
           result = a / b;
        }
        catch (DivideByZeroException)
        {
           Console.WriteLine("Exception occured");
        }
        finally
        {
           Console.WriteLine("Result: {0}", result);
        }

User Defined Exceptions

User defined exceptions are custom exceptions that can be created by the users. This is done by inheriting the exception class.

A program that demonstrates user defined exceptions is given as follows:

Source Code: Program that demonstrates user defined exceptions in C#

using System;
namespace UserDefinedExceptionDemo
{
  class Example
  {
     static void Main(string[] args)
     {
        Age a = new Age();
        try
        {
           a.displayAge();
        }
        catch(AgeIsNegativeException e)
        {
           Console.WriteLine("AgeIsNegativeException: {0}", e.Message);
        }
     }
  }
}
public class AgeIsNegativeException: Exception
{
  public AgeIsNegativeException(string message): base(message)
  {
  }
}
public class Age
{
  int age = -5;
  public void displayAge()
  {
     if(age < 0)
     {
        throw (new AgeIsNegativeException("Age cannot be negative"));
     }
     else
     {
        Console.WriteLine("Age is: {0}", age);
     }
  }
}

The output of the above program is as follows:

AgeIsNegativeException: Age cannot be negative

Now let us understand the above program.

The try and catch blocks are available in the Main() function. The displayAge() function is called in the try block. If the age is less than zero, then an exception message is printed in the catch block because the age cannot be less than zero. The code snippet for this is as follows:

 static void Main(string[] args)
     {
        Age a = new Age();
        try
        {
           a.displayAge();
        }
        catch(AgeIsNegativeException e)
        {
           Console.WriteLine("AgeIsNegativeException: {0}", e.Message);
        }
     }

The variable of type int is declared in class Age. The function displayAge() throws an exception if the age is less than zero. Otherwise, it prints the age. The code snippet for this is as follows:

public class Age
{
  int age = -5;
  public void displayAge()
  {
     if(age < 0)
     {
        throw (new AgeIsNegativeException("Age cannot be negative"));
     }
     else
     {
        Console.WriteLine("Age is: {0}", age);
     }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

austin faith

Avery good write-up. Please let me know what are the types of C# libraries used for AI development.

kariya arti

very satisfied!!

jean-Francois Michaud

Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).

Kshitiz

Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz

Ed

The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial