1. What is Exception Handling?
Exception Handling is a mechanism to detect and handle runtime errors so
that the normal flow of the program can be maintained.
✅ 2. Keywords Used
Keywor
Description
d
Contains the code that might throw an
try
exception.
catch Handles the exception thrown in the try block.
Always executes, whether or not an exception
finally
occurred.
throw Used to throw exceptions manually.
✅ 3. Basic Syntax
csharp
CopyEdit
try
{
// Code that may cause an exception
}catch (ExceptionType ex)
{
// Code to handle the exception
}finally
{
// Code that always runs
}
✅ 4. Common Exception Types
Exception Type Description
System.Exception Base class for all exceptions.
System.NullReferenceExceptio
Thrown when using an object that is null.
n
System.DivideByZeroExceptio
Thrown when dividing by zero.
n
System.IndexOutOfRangeExce Thrown when accessing an array index out
ption of range.
System.IO.IOException Thrown for I/O failures.
✅ 5. Example: Simple Exception Handling
csharp
CopyEdit
class Program
{
static void Main()
{
try
{
int a = 10, b = 0;
int result = a / b;
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
Console.WriteLine("Finally block executed.");
}
}
}
✅ 6. Multiple Catch Blocks
csharp
CopyEdit
try
{
int[] arr = new int[3];
Console.WriteLine(arr[5]);
}catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index error: " + ex.Message);
}catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}
✅ 7. Throwing Exceptions
csharp
CopyEdit
public void CheckAge(int age)
{
if (age < 18)
{
throw new ArgumentException("Age must be 18 or above.");
}
}
✅ 8. Custom Exceptions
csharp
CopyEdit
public class AgeTooSmallException : Exception
{
public AgeTooSmallException(string message) : base(message) { }
}
csharp
CopyEdit
// Usageif (age < 18)
throw new AgeTooSmallException("Custom: Age is too small.");
✅ 9. Exception Filters (C# 6 and above)
csharp
CopyEdit
try
{
// Code
}catch (Exception ex) when (ex.Message.Contains("specific"))
{
Console.WriteLine("Filtered exception.");
}
✅ 10. Best Practices
✅ Catch only specific exceptions.
✅ Log exception details.
✅ Don’t suppress exceptions silently.
✅ Avoid using exceptions for control flow.
✅ Clean up resources in finally or use using for disposable objects.
🧠 Real-Time Example: File Reading
csharp
CopyEdit
using System.IO;
try
{
string text = File.ReadAllText("sample.txt");
Console.WriteLine(text);
}catch (FileNotFoundException ex)
{
Console.WriteLine("File not found: " + ex.Message);
}catch (IOException ex)
{
Console.WriteLine("IO error: " + ex.Message);
}
❓Interview Questions with Answers
Q1: What is the difference between throw and throw ex?
A: throw preserves the original stack trace; throw ex resets it — use throw for
better debugging.
Q2: Can a finally block exist without a catch block?
A: Yes. You can use try-finally without a catch block.
Q3: What happens if there is an exception in finally?
A: It can override an exception from the try block. Avoid throwing exceptions
from finally.
Q4: Can multiple catch blocks handle one exception?
A: No. The first matching catch block handles the exception.
Q5: What is the purpose of custom exceptions?
A: To provide meaningful and domain-specific error handling.
🧪 Skill Test (with Answers)
❓ Q1: What is wrong with this code?
csharp
CopyEdit
try
{
int x = 5 / 0;
}catch (Exception)
{
Console.WriteLine("Error");
}finally
{
return;
}
Console.WriteLine("Done");
Answer: return in finally causes Console.WriteLine("Done") to never execute.
❓ Q2: Output?
csharp
CopyEdit
try
{
Console.WriteLine("Try");
throw new Exception("Error");
}catch
{
Console.WriteLine("Catch");
}finally
{
Console.WriteLine("Finally");
}
Output:
vbnet
CopyEdit
TryCatchFinally
🧠 6 Complex Interview Questions
Q1: How would you handle an exception that occurs inside a using block?
csharp
CopyEdit
using (StreamReader reader = new StreamReader("file.txt"))
{
try
{
string line = reader.ReadToEnd();
}
catch (IOException ex)
{
// Handle
}
}
Q2: Can you log and rethrow an exception? How?
csharp
CopyEdit
try
{
// Code
}catch (Exception ex)
{
Console.WriteLine("Log: " + ex.Message);
throw; // Rethrows while preserving stack trace
}
Q3: Write a method that catches all exceptions but only logs and doesn't
halt execution.
csharp
CopyEdit
public void SafeExecute(Action action)
{
try
{
action();
}
catch (Exception ex)
{
Console.WriteLine("Logged: " + ex.Message);
}
}
Q4: Can you prevent catching of exceptions that you don’t expect?
csharp
CopyEdit
try
{
// Do something
}catch (SpecificException ex)
{
// Handle only known exceptions
throw;
}
Q5: Create a retry mechanism using try-catch
csharp
CopyEdit
int attempts = 0;bool success = false;while (attempts < 3 && !success)
{
try
{
// Try code
success = true;
}
catch (Exception)
{
attempts++;
}
}
Q6: What is the impact of not releasing unmanaged resources during
exceptions?
Answer: It leads to memory leaks or locked resources like open files or DB
connections. Use finally or using to avoid this.
OOPs in C#: Classes and Objects
🔹 What is OOP (Object-Oriented Programming)?
OOP is a programming paradigm based on the concept of “objects,” which can
contain data (fields) and code (methods). C# is a fully object-oriented
language.
🧱 1. Classes in C#
🔹 What is a Class?
A class is a blueprint for creating objects. It defines properties (fields),
methods, constructors, events, and indexers.
🔹 Syntax:
csharp
CopyEdit
public class Car
{
// Fields
public string Brand;
public string Color;
// Method
public void Drive()
{
Console.WriteLine("The car is driving.");
}
}
🔹 Real-world analogy:
A Class is like an architectural blueprint of a house. It tells how a house
should be but isn’t a house itself.
🧍 2. Objects in C#
🔹 What is an Object?
An object is an instance of a class. It occupies memory and performs actual
operations defined in the class.
🔹 Syntax:
csharp
CopyEdit
Car myCar = new Car(); // Object creation
myCar.Brand = "Toyota"; // Setting fields
myCar.Color = "Red";
myCar.Drive(); // Calling method
🔄 3. Class vs Object (Comparison)
Feature Class Object
Definition Blueprint or template Instance of a class
Takes memory when
Memory No memory allocation
created
Defines
Usage Performs actual tasks
properties/methods
Declaratio
public class Car {} Car c1 = new Car();
n
4. Components of a Class
Fields: Variables that hold data
Properties: Encapsulated fields (used with getters/setters)
Methods: Actions the object can perform
Constructors: Special methods to initialize objects
Destructors: Clean-up code when object is destroyed
Access Modifiers: public, private, protected, etc.
🧪 5. Example with Constructor
csharp
CopyEdit
public class Student
{
public string Name;
public int Age;
// Constructor
public Student(string name, int age)
{
Name = name;
Age = age;
}
public void Display()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
csharp
CopyEdit
Student s1 = new Student("Rupa", 20);
s1.Display(); // Output: Name: Rupa, Age: 20
🧠 6. Real-world Analogy of Object
Class: MobilePhone
Object: Your specific iPhone or Samsung device
Field: ModelName, Price
Method: MakeCall(), SendSMS()
🔐 7. Access Modifiers in Class
Modifie
Description
r
public Accessible from anywhere
private Accessible only inside the class
protecte Accessible in the class and derived
d classes
Accessible within the same
internal
assembly
🧪 Coding Practice
Problem:
Create a Book class with properties Title, Author, and method
DisplayBookDetails.
csharp
CopyEdit
public class Book
{
public string Title;
public string Author;
public void DisplayBookDetails()
{
Console.WriteLine($"Book: {Title}, Author: {Author}");
}
}
// Usage
Book b1 = new Book();
b1.Title = "The Alchemist";
b1.Author = "Paulo Coelho";
b1.DisplayBookDetails();
💬 Interview Questions
✅ Basic:
1.
What is the difference between a class and an object?
2.
3.
How do you create and initialize an object in C#?
4.
5.
What is the role of constructors in a class?
6.
🧠 Advanced:
1.
Can a class have multiple constructors? What is constructor overloading?
2.
3.
What is the difference between reference and value types in terms of
objects?
4.
5.
Explain how memory is allocated to class instances.
6.