Exception Handling in C Sharp Language

Exception Handling in C# Language

Exception handling is an essential concept in programming, as it allows developers to manage and gracefully recover from unexpected errors and issues that can occur during the executi

on of a program. In C#, the exception handling mechanism provides a structured way to deal with these situations, ensuring that your application remains robust and stable. In this post, we will explore the fundamentals of exception handling in C# and provide examples to illustrate its usage.

An exception in C# is an object that represents an abnormal condition during the program’s execution. These abnormal conditions can include runtime errors, such as divide-by-zero, file not found, or null reference exceptions. When an exception is thrown, it disrupts the normal flow of the program and transfers control to an appropriate exception handler.

Exception Handling Keywords

C# provides several keywords to work with exceptions:

  1. try: The try block contains the code where exceptions may occur.
  2. catch: The catch block handles exceptions by specifying the type of exception it can catch. Multiple catch blocks can be used to handle different types of exceptions.
  3. finally: The finally block contains code that is executed regardless of whether an exception is thrown or not. It’s used for cleanup or resource release.
  4. throw: The throw keyword is used to explicitly raise an exception.
  5. using: This keyword is used for resource management and ensures that resources like files or database connections are properly disposed of, even if an exception is thrown.

Example of Exception Handling

Let’s look at a simple example to understand exception handling in C#:

using System;

class Program
{
    static void Main()
    {
        int numerator = 10;
        int denominator = 0;
        try
        {
            int result = numerator / denominator; // This line will throw a DivideByZeroException.
            Console.WriteLine("Result: " + result);
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Exception caught: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Finally block executed.");
        }
    }
}

In this example, we attempt to divide by zero, which would throw a DivideByZeroException. The try block contains the code that might cause an exception. In this case, it attempts to divide by zero. The catch block catches the exception, and we can handle it by displaying an error message. The finally block is executed regardless of whether an exception is thrown or not, making it suitable for cleanup operations.

Custom Exceptions

In addition to built-in exceptions, C# allows you to create custom exceptions by extending the Exception class. Custom exceptions are useful when you want to define application-specific error types.

using System;

public class CustomException : Exception
{
    public CustomException(string message) : base(message)
    {
    }
}

class Program
{
    static void Main()
    {
        try
        {
            throw new CustomException("This is a custom exception.");
        }
        catch (CustomException ex)
        {
            Console.WriteLine("Custom Exception caught: " + ex.Message);
        }
    }
}

Custom exceptions can be caught and handled in the same way as built-in exceptions.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading