CHAPTER 19
Beginner
Exception Handling in C#
Updated: May 17, 2026
5 min read
# CHAPTER 19
Exception Handling
1. Introduction
No matter how perfectly you write your code, things will go wrong at runtime. A user types text when you asked for a number. A database server goes offline. A file is deleted. If you don't handle these Exceptions, your application will abruptly crash. Exception Handling allows you to intercept errors, report them gracefully, and keep the program running.2. Learning Objectives
By the end of this chapter, you will be able to:-
Understand the
try,catch, andfinallyblocks.
- Catch specific types of exceptions.
-
Use the
throwkeyword.
-
Ensure resources are cleaned up using
finally.
3. The try and catch Blocks
-
try: A block of code you suspect might cause an error.
-
catch: The block of code that executes *only if* an error occurs inside thetryblock.
csharp
4. Catching Specific Exceptions
Atry block can have multiple catch blocks. It is best practice to catch specific, anticipated errors first, and leave the generic Exception class at the bottom as a catch-all safety net.
csharp
5. The finally Block
The finally block is placed after the catch blocks. The code inside finally is GUARANTEED to execute, regardless of whether an exception occurred or not. It is typically used to close database connections or open files, ensuring memory isn't locked.
csharp
6. The throw Keyword
You can manually trigger an exception if your code detects a logical error (e.g., an age cannot be negative).
csharp
7. Mini Project: Safe Calculator
csharp
8. Common Mistakes
-
Empty Catch Blocks: Writing
catch (Exception) { }and doing nothing inside it is called "swallowing" the exception. It hides bugs and makes debugging impossible. At least log the error to the console!
-
Using Try-Catch for Control Flow: Do not use exceptions to control normal program logic. Exceptions are computationally expensive. Use an
ifstatement to check if a string is null, don't just let it throw aNullReferenceException.
9. Best Practices
-
Catch specific exceptions (like
FileNotFoundException) instead of always catching the genericException.
-
Use the
ex.Messageorex.StackTraceproperties to log detailed information for debugging.
10. Exercises
-
1.
Write a program that accesses the 10th element of a 3-element array. Wrap it in a
try-catchblock that specifically catchesIndexOutOfRangeException.
-
2.
Add a
finallyblock that prints "Execution finished."
11. MCQs with Answers
Question 1
Which block contains the code that might cause a runtime error?
Question 2
Which block contains the code that handles the error?
Question 3
Which block is guaranteed to execute, regardless of whether an error occurred or not?
Question 4
Which keyword is used to manually generate an exception?
Question 5
What is the base class for all exceptions in C#?
Question 6
What happens if an exception is thrown but there is no catch block to handle it?
Question 7
When chaining multiple catch blocks, where must the generic catch (Exception ex) be placed?
Question 8
Which exception is thrown when you divide an integer by 0?
Question 9
Which exception is thrown when int.Parse() fails to convert letters to a number?
12. Interview Questions
-
Q: Explain the exact execution flow of
try,catch, andfinally.
-
Q: Why should you avoid catching the generic
Exceptionbase class if possible?
-
Q: What is the difference between
throw;andthrow ex;inside a catch block? (Answer:throw;preserves the original stack trace, whilethrow ex;resets the stack trace to the catch block, making debugging harder).
13. Summary
Exception handling acts as a safety net. Thetry block attempts risky code, the catch block gracefully intercepts and manages crashes, and the finally block ensures critical cleanup happens no matter what. Using throw, you can manually enforce logical rules in your application.
14. Next Chapter Recommendation
In Chapter 20: Generics and Collections, we will revisitList<T> and explore how the <T> syntax (Generics) allows us to write highly reusable, type-safe data structures.