C# Interview Questions
C# Programming
Web DevelopmentFrontendBackendGame DevQuestion 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
-
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.
-
Try-Catch-Finally:
try
: The block of code that might throw an exception is enclosed within atry
block.catch
: The block of code that handles the exception is enclosed within acatch
block. Multiplecatch
blocks can be used to handle different types of exceptions.finally
: Thefinally
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
-
Specific Catch Blocks:
- Catch specific exceptions before catching the general
Exception
type to handle different error types appropriately.
- Catch specific exceptions before catching the general
-
Avoid Empty Catch Blocks:
- Always handle exceptions or log them; avoid catching exceptions without any action as it hides potential issues.
-
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.
- Use the
-
Exception Propagation:
- Rethrow exceptions when necessary to allow higher-level code to handle them appropriately, using
throw;
to maintain the original stack trace.
- Rethrow exceptions when necessary to allow higher-level code to handle them appropriately, using
-
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 aDivideByZeroException
if the denominator is zero. - The
Main
method uses atry-catch-finally
block to handle the exception, output an error message, and ensure that thefinally
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.