---
title: "Explain about the Exception handing in C# with example?"  
description: "Explain about the Exception handing in C# with example?"  
author: "Ethan Karla"  
published: 2021-08-27  
updated: 2023-04-20  
canonical: https://answers.mindstick.com/qa/93940/explain-about-the-exception-handing-in-c-sharp-with-example  
category: "programming"  
tags: ["c#", "java", "pythons"]  
reading_time: 9 minutes  

---

# Explain about the Exception handing in C# with example?

[Explain](https://yourviews.mindstick.com/view/86025/content-created-for-humans-not-for-bots-explain-this-statement) about the [Exception](https://www.mindstick.com/articles/61/exception-handling-in-c-sharp) handing in C# with example?

## Answers

### Answer by Ravi Vishwakarma

**C# Exception** We know that there are two types of error, one is compile-time and the other is run time. The compile-time error is known only when we write the program and compile the program. But the run time error is detected when we run or execute the program. We use exception handling to catch this run time error. So the job of Exception Handling is to catch the run time error. \
**C# Exception handling is made by four keywords try, catch, finally, and throw.**

1. Try - The code in which the exception is likely to occur is placed in the try block.
2. Catch - Exception is caught in this block. The catch keyword is used to catch it.
3. Finally - finally block is used so that whether the exception comes or not the code has to be executed! For example, if you open a file to read or write, then it is also necessary to close that file. That's why we use finally block for this work.
4. Throw - A program throws an exception when there is a problem in that program. For this throw keyword is used.

**Syntax**

```
try {
// If such codes are kept in this block, then there is a possibility of an exception coming.
}
catch( Exception-class e1 )
{
// exception is caught in this block
}
finally
{
// In this block the code is kept which has to be executed
}
```

\
The **Exception class** in C# is derived from the System.Exception class. There are two types of Sytem.Exception class, one is **System.ApplicationException** and the other is **System.SystemException** class.

1. System.ApplicationException - The System.ApplicationException class supports exceptions that are generated from the application program.
2. System.SystemException - System.SystemException class is the base class of all predefined exceptions in the System.

**Some predefined exception classes are shown below** 1. System.IO.IOException: This class handles Input/Output errors! 2. System.IndexOutOfRangeException: This class handles the error in which a method shows the array index out of range. 3. System.ArrayTypeMismatchException: This class handles the error when the type is mismatched with the array type. 4. System.NullReferenceException: This class handles the error when referencing a null object. 5. System.DivideByZeroException: This class handles the error when someone divides a number by zero. 6. System.InvalidCastException: This class handles the error when the typecasting is invalid. 7. System.OutOfMemoryException: This class handles the error when there is a lack of memory. 8. System.StackOverflowException: This class handles the error when the stack overflows. **Example**

```
using System;
namespace ExceptionHandling {
 class DivisionofNumber {
  int res = 0 ;
  public void division(int num1, int num2) {
   try {
   res = num1 / num2;
   }
   catch (DivideByZeroException e)
   {
   Console.WriteLine('Exception is : {0}',e);
   }
   finally
   {
   Console.WriteLine('Result is : {0}',res);
    res = 0;
   }
  }
  public static void Main()	{
   DivisionofNumber divObj = new DivisionofNumber();
   divObj.division(25, 2); // no exception arise
   divObj.division(25, 0); // exception arise
   Console.ReadKey();
  }
 }
}
```

**Output**

```
Result is: 12
Exception is: System.DivideByZeroException: Attempted to divide by zero.
   at DivisionofNumber.division(Int32 num1, Int32 num2)
Result is : 0
```

\

### Answer by Revati S Misra

Exception handling is a way to gracefully handle runtime errors in a C# program. When an error occurs during the execution of a program, an exception is thrown, which can be caught and handled in a try-catch block. Here's an example:

```cs
try
{
    // Code that may throw an exception
    int x = 10 / 0; // This will throw a divide by zero exception
}
catch (DivideByZeroException ex)
{
    // Handle the exception
    Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
    // Code that will always execute, regardless of whether an exception was thrown or not
    Console.WriteLine("The program has finished executing.");
}
```

In this example, we have a try-catch-finally block. The code inside the try block attempts to divide the number 10 by zero, which is an illegal operation and will throw a DivideByZeroException.

When the exception is thrown, the catch block catches it and executes its code. In this case, we simply print an error message that includes the exception message.

The **finally** block is optional and will always execute, regardless of whether an exception was thrown or not. In this example, we print a message that indicates the program has finished executing.

There are other types of exceptions that can be caught, such as ArgumentException, ArgumentNullException, **IndexOutOfRangeException**, and so on. It's important to catch only the specific exceptions that you expect might be thrown and to handle them appropriately.

In addition to try-catch-finally blocks, C# also provides the throw statement, which allows you to manually throw an exception. This can be useful when you want to create a custom exception that isn't already provided by the .NET Framework.

```cs
if (x < 0)
{
    throw new ArgumentException("x must be a positive integer.");
}
```

In this example, we use the throw statement to manually throw an **ArgumentException** if the variable x is less than zero. We pass a string message to the constructor of the ArgumentException, which will be displayed when the exception is caught and handled.

### Answer by user

An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: **try**, **catch**, **finally**, and **throw**.

**try** − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.

**catch** − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

**finally** − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

**throw** − A program throws an exception when a problem shows up. This is done using a throw keyword.

## Syntax

Assuming a block raises an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following −

```cs
using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;

      DivNumbers() {
         result = 0;
      }
      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}
```

You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.

## Exception Classes in C#

C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the **System.Exception** class. Some of the exception classes derived from the System.Exception class are the **System.ApplicationException** and **System.SystemException** classes.

The **System.ApplicationException** class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class.

The **System.SystemException** class is the base class for all predefined system exception.

The following table provides some of the predefined exception classes derived from the Sytem.SystemException class −

## Handling Exceptions

C# provides a structured solution to the exception handling in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements.

These error handling blocks are implemented using the **try**, **catch**, and **finally** keywords. Following is an example of throwing an exception when dividing by zero condition occurs −

Live Demo

```cs
using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;

      DivNumbers() {
         result = 0;
      }
      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}
```

When the above code is compiled and executed, it produces the following result −

```cs
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
```

## Creating User-Defined Exceptions

You can also define your own exception. User-defined exception classes are derived from the **Exception** class. The following example demonstrates this −

```cs
using System;

namespace UserDefinedException {
   class TestTemperature {
      static void Main(string[] args) {
         Temperature temp = new Temperature();
         try {
            temp.showTemp();
         } catch(TempIsZeroException e) {
            Console.WriteLine("TempIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}
public class TempIsZeroException: Exception {
   public TempIsZeroException(string message): base(message) {
   }
}
public class Temperature {
   int temperature = 0;

   public void showTemp() {

      if(temperature == 0) {
         throw (new TempIsZeroException("Zero Temperature found"));
      } else {
         Console.WriteLine("Temperature: {0}", temperature);
      }
   }
}
```

When the above code is compiled and executed, it produces the following result −

```cs
TempIsZeroException: Zero Temperature found
```

## Throwing Objects

You can throw an object if it is either directly or indirectly derived from the **System.Exception** class. You can use a throw statement in the catch block to throw the present object as −

```cs
Catch(Exception e) {
   ...
   Throw e
}
```


---

Original Source: https://answers.mindstick.com/qa/93940/explain-about-the-exception-handing-in-c-sharp-with-example

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
