Exception Handling in C#
What is an Exception?
An exception is a runtime error that disrupts the normal flow of a program. Examples
include:
Dividing by zero
File not found
Null reference
Exception Handling Syntax
try
{
// Code that may throw an exception
}
catch (ExceptionType ex)
{
// Handle exception
}
finally
{
// Cleanup code (optional)
}
Common Exception Types
Exception Type Description
DivideByZeroException Thrown when dividing by zero
NullReferenceException Accessing object that is null
IndexOutOfRangeExcep
Array index out of range
tion
FileNotFoundException File not found during file operation
Invalid type conversion (e.g., string
FormatException
to int)
Real-World Example
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Error
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index out of range: " + ex.Message);
}
finally
{
Console.WriteLine("Always runs (e.g., close files or connections)");
}
1
Multiple Catch Blocks
try
{
// risky code
}
catch (NullReferenceException ex)
{
Console.WriteLine("Null reference: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}
Throwing Exceptions
throw new InvalidOperationException("Invalid operation");
Custom Exceptions
public class AgeException : Exception
{
public AgeException(string message) : base(message)
{
}
}
// Usage
if (age < 18)
throw new AgeException("Age must be 18 or older.");
Best Practices
Catch only specific exceptions
Use finally for cleanup
Don’t swallow exceptions silently
Log exception details
Avoid throwing exceptions in loops
Interview Questions & Answers
1: What is the difference between throw and throw ex?
A: throw preserves the original stack trace; throw ex resets it.
2: What does the finally block do?
A: Executes whether an exception occurs or not; used for cleanup.
3: Can you catch multiple exceptions?
A: Yes, using multiple catch blocks or a single catch(Exception) for general handling.
4: What happens if an exception is not handled?
A: The application crashes and displays the error message.
2
5: Can we have a try block without catch?
A: Yes, but only if finally is present.
Skill Test
1: Predict the output:
try
{
int x = 5 / 0;
}
catch (DivideByZeroException)
{
Console.WriteLine("Can't divide by zero.");
}
finally
{
Console.WriteLine("Finally block executed.");
}
Ans: Can't divide by zero. Finally block executed.
2: Catch Order
try
{
string s = null;
Console.WriteLine(s.Length);
}
catch (Exception ex)
{
Console.WriteLine("General exception caught.");
}
catch (NullReferenceException ex)
{
Console.WriteLine("Null reference caught.");
}
What will be the output?
Ans: Compilation error – The more specific NullReferenceException must come before
the general Exception in the catch order.
3. Finally Without Exception
try
{
Console.WriteLine("Inside try block.");
}
catch (Exception)
{
Console.WriteLine("Inside catch block.");
}
finally
{
Console.WriteLine("Inside finally block.");
}
3
What is the output?
Ans:
Inside try block.
Inside finally block.
4. Custom Exception Usage
public class InvalidAgeException : Exception
{
public InvalidAgeException(string message) : base(message)
{
}
}
int age = 15;
try
{
if (age < 18)
throw new InvalidAgeException("Age must be 18+");
}
catch (InvalidAgeException ex)
{
Console.WriteLine(ex.Message);
}
What is the output?
Ans: Age must be 18+
5.Return in Try and Finally
static int Test()
{
try
{
return 1;
}
finally
{
return 2;
}
}
Console.WriteLine(Test());
What will this print?
Ans: 2 – The finally block overrides the return value from the try.
6.Unhandled Exception
try
{
int[] arr = new int[3];
4
arr[10] = 100;
}
catch (DivideByZeroException)
{
Console.WriteLine("Divide by zero error.");
}
What will happen?
Ans: Unhandled exception: IndexOutOfRangeException
– It's not caught because only DivideByZeroException is handled.