Explain about the Exception handing in C# with example?

Asked 27-Aug-2021
Updated 20-Apr-2023
Viewed 902 times

0

Explain about the Exception handing in C# with example?


2 Answers


0

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:

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.

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.


1

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