Ticker

6/recent/ticker-posts

Exception handling in C#

 Exception handling in C#



Exception handling in C# is a mechanism that allows developers to handle and manage runtime errors or exceptional conditions that may occur during the execution of a program. It helps prevent the program from crashing abruptly and provides a way to gracefully handle errors, log them, and take appropriate actions.

 

In C#, exception handling is done using try-catch blocks. The code that might raise an exception is placed within the try block, and the handling code is placed within the catch block.

 

Here's an example:

 


try
{
    // Code that may raise an exception
    int a = 10;
    int b = 0;
    int result = a / b;
    Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
    // Handling code for DivideByZeroException
    Console.WriteLine("Cannot divide by zero.");
    Console.WriteLine("Error Message: " + ex.Message);
}
catch (Exception ex)
{
    // Generic exception handling code
    Console.WriteLine("An error occurred.");
    Console.WriteLine("Error Message: " + ex.Message);
}
finally
{
    // Optional finally block to execute regardless of whether an exception occurred or not
    Console.WriteLine("Cleanup code goes here.");
}

In the above code, the division operation `a / b` inside the try block may raise a `DivideByZeroException` if the value of `b` is zero. If this exception occurs, the program flow is transferred to the corresponding catch block, which handles the exception.

 

If a `DivideByZeroException` is caught, the catch block displays an error message indicating that division by zero is not allowed, along with the exception message. If any other exception occurs, the generic catch block handles it by displaying a general error message.

 

The finally block is optional and is used for cleanup tasks that need to be executed regardless of whether an exception occurred or not. It is commonly used to release resources or close connections.

 

Exception handling provides a structured way to handle and recover from runtime errors. By catching and handling exceptions, you can gracefully handle errors, log them for debugging purposes, and ensure that your program continues executing without crashing unexpectedly.

Exception handling in C#

Exception handling in C# is a mechanism that allows you to handle and recover from runtime errors or exceptional conditions that may occur during the execution of a program. It helps prevent unexpected crashes and allows you to gracefully handle and respond to errors.

 

In C#, exceptions are represented by objects derived from the `System.Exception` class. When an exceptional condition occurs, an exception object is thrown, and the normal flow of the program is interrupted. To handle exceptions, you can use the `try-catch-finally` statement.

 

Here's an example that demonstrates exception handling in C#:

 


try
{
    // Code that may throw an exception
    int result = Divide(10, 0);
    Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
    // Exception handling code for DivideByZeroException
    Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
catch (Exception ex)
{
    // Generic exception handling code
    Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
    // Code that will always be executed, regardless of whether an exception occurred or not
    Console.WriteLine("Cleanup code");
}

// Other code continues...

In the example above, the `try` block contains the code that may throw an exception. In this case, the `Divide` method is called with arguments (10, 0), which will result in a `DivideByZeroException` being thrown.

 

If a `DivideByZeroException` is thrown, the execution flow is transferred to the corresponding `catch` block. In this block, you can handle the exception by providing specific code to be executed when the exception occurs. In this case, we print a custom error message.

 

If a different type of exception occurs, it will be caught by the generic `Exception` catch block. This allows you to handle any unexpected exceptions that may occur.

 

The `finally` block is optional and is used to specify code that will be executed regardless of whether an exception occurred or not. It is typically used for cleanup operations, such as closing files or releasing resources.

 

After the exception is handled (or not caught at all), the program continues its normal execution from the point immediately after the `try-catch-finally` block.

 

Exception handling allows you to gracefully handle errors and take appropriate actions, such as displaying error messages, logging the exception details, or performing recovery operations. By using appropriate exception handling techniques, you can make your programs more robust and resilient.

The `throw` keyword in C#

The `throw` keyword in C# is used to explicitly raise an exception. It is typically used when an exceptional condition occurs during the execution of a program, and you want to signal that something unexpected has happened.

 

When you use the `throw` keyword, you provide an instance of an exception class that represents the specific type of exception you want to throw. This exception object contains information about the exception, such as an error message and a stack trace.

 

Here's an example code snippet that demonstrates the usage of the `throw` keyword:

 


public class CustomException : Exception
{
    // CustomException implementation
}

public class Calculator
{
    public int Divide(int numerator, int denominator)
    {
        if (denominator == 0)
        {
            // Throwing a custom exception when division by zero occurs
            throw new CustomException("Cannot divide by zero.");
        }

        return numerator / denominator;
    }
}

public class Program
{
    public static void Main()
    {
        Calculator calculator = new Calculator();

        try
        {
            int result = calculator.Divide(10, 0);
            Console.WriteLine("Result: " + result);
        }
        catch (CustomException ex)
        {
            Console.WriteLine("Exception caught: " + ex.Message);
        }
    }
}

In the above code, the `Divide` method of the `Calculator` class checks if the `denominator` is zero. If it is, the `throw` keyword is used to throw a `CustomException` with the message "Cannot divide by zero."

 

In the `Main` method, we create an instance of `Calculator` and attempt to divide 10 by 0, which triggers the exception. The `try-catch` block is used to catch the `CustomException` and handle it accordingly. In this case, we simply print the exception message.

 

Using the `throw` keyword allows you to control the flow of your program when exceptional situations occur, enabling you to handle and respond to errors appropriately.

Working with custom exceptions in C#

Working with custom exceptions in C# involves creating and handling exceptions that are specific to your application or domain. By creating custom exceptions, you can provide more meaningful error messages and handle exceptional situations in a more specialized manner.

 

Here's an example of how to work with custom exceptions in C#:


using System;

// Custom exception class
public class InvalidInputException : Exception
{
    public InvalidInputException(string message) : base(message)
    {
    }
}

// Custom class that throws the custom exception
public class Calculator
{
    public int Divide(int dividend, int divisor)
    {
        if (divisor == 0)
        {
            throw new InvalidInputException("Divisor cannot be zero.");
        }

        return dividend / divisor;
    }
}

// Usage example
public class Program
{
    public static void Main()
    {
        Calculator calculator = new Calculator();

        try
        {
            int result = calculator.Divide(10, 0);
            Console.WriteLine($"Result: {result}");
        }
        catch (InvalidInputException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Unexpected error occurred: {ex.Message}");
        }
    }
}

In the above code, we define a custom exception class `InvalidInputException` that inherits from the base `Exception` class. It has a constructor that takes a message parameter and passes it to the base class constructor using `base(message)`.

 

The `Calculator` class represents a simple calculator and contains a `Divide` method that throws the `InvalidInputException` if the divisor is zero. The `Main` method demonstrates the usage of the `Calculator` class and handles the custom exception by catching `InvalidInputException` specifically. If any other unexpected exception occurs, it is caught by the general `Exception` catch block.

 

When executing the code, if we pass 0 as the divisor in the `Divide` method, it will throw the `InvalidInputException`, and the catch block for that specific exception will be triggered. The custom exception message "Divisor cannot be zero." will be displayed.

 

By creating custom exceptions, you can differentiate between different exceptional situations in your code and handle them appropriately. This allows for better error management and more informative error messages to aid in debugging and troubleshooting.

Post a Comment

0 Comments