C# Interview Questions

36 Questions
C# Programming

C# Programming

Web DevelopmentFrontendBackendGame Dev

Question 19

What is exception handling in C#?

Answer:

Exception handling in C# is a mechanism that provides a structured and unified way of handling runtime errors and exceptional conditions that occur during the execution of a program. This mechanism helps to manage errors gracefully, ensuring that the application can respond appropriately rather than crashing unexpectedly.

Key Concepts of Exception Handling

  1. Exception:

    • An exception is an object that encapsulates information about an error or an unexpected event that occurs during the execution of a program.
    • Exceptions can be generated by the .NET runtime or explicitly thrown by the code using the throw statement.
  2. Try-Catch-Finally:

    • try: The block of code that might throw an exception is enclosed within a try block.
    • catch: The block of code that handles the exception is enclosed within a catch block. Multiple catch blocks can be used to handle different types of exceptions.
    • finally: The finally block contains code that executes regardless of whether an exception was thrown or not. It is typically used for cleanup operations.

Basic Syntax

Try-Catch Block

try
{
    // Code that might throw an exception
    int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
    // Handle the specific exception
    Console.WriteLine("Cannot divide by zero.");
}
catch (Exception ex)
{
    // Handle any other exceptions
    Console.WriteLine($"An error occurred: {ex.Message}");
}

Finally Block

try
{
    // Code that might throw an exception
    int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
    // Handle the specific exception
    Console.WriteLine("Cannot divide by zero.");
}
catch (Exception ex)
{
    // Handle any other exceptions
    Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
    // Code that will always execute
    Console.WriteLine("Finally block executed.");
}

Throwing Exceptions

You can explicitly throw exceptions using the throw statement:

public void Divide(int numerator, int denominator)
{
    if (denominator == 0)
    {
        throw new DivideByZeroException("Denominator cannot be zero.");
    }
    int result = numerator / denominator;
}

Custom Exceptions

You can create custom exceptions by inheriting from the Exception class:

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

// Usage
try
{
    throw new MyCustomException("This is a custom exception.");
}
catch (MyCustomException ex)
{
    Console.WriteLine(ex.Message);
}

Exception Properties

  • Message: A text message that describes the error.
  • StackTrace: A string representation of the call stack at the point the exception was thrown.
  • InnerException: The exception that caused the current exception, useful for exception chaining.

Best Practices

  1. Specific Catch Blocks:

    • Catch specific exceptions before catching the general Exception type to handle different error types appropriately.
  2. Avoid Empty Catch Blocks:

    • Always handle exceptions or log them; avoid catching exceptions without any action as it hides potential issues.
  3. Use Finally for Cleanup:

    • Use the finally block to release resources like file handles, network connections, or database connections, ensuring they are released regardless of success or failure.
  4. Exception Propagation:

    • Rethrow exceptions when necessary to allow higher-level code to handle them appropriately, using throw; to maintain the original stack trace.
  5. Custom Exceptions:

    • Create custom exceptions for specific error conditions in your application to provide more meaningful error information.

Example of Exception Handling

using System;

public class Program
{
    public static void Main()
    {
        try
        {
            int result = Divide(10, 0);
            Console.WriteLine($"Result: {result}");
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("An unexpected error occurred: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Execution completed.");
        }
    }

    public static int Divide(int numerator, int denominator)
    {
        if (denominator == 0)
        {
            throw new DivideByZeroException("Denominator cannot be zero.");
        }
        return numerator / denominator;
    }
}

In this example:

  • The Divide method throws a DivideByZeroException if the denominator is zero.
  • The Main method uses a try-catch-finally block to handle the exception, output an error message, and ensure that the finally block is executed regardless of the outcome.

Conclusion

Exception handling in C# is a powerful feature that helps manage runtime errors and unexpected conditions gracefully. By using try, catch, and finally blocks, and creating custom exceptions, you can write robust and maintainable code that handles errors effectively and ensures proper resource management.

Recent job openings