Exception handling helps your program deal with unexpected problems without crashing. It keeps your program running smoothly and lets you fix errors nicely.
Why exception handling is needed in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
C Sharp (C#)
try { // code that might cause an error } catch (ExceptionType e) { // code to handle the error } finally { // code that runs no matter what }
try block contains code that might cause an error.
catch block handles the error if it happens.
Examples
C Sharp (C#)
try { int result = 10 / 0; } catch (DivideByZeroException e) { Console.WriteLine("Cannot divide by zero."); }
C Sharp (C#)
try { string text = null; Console.WriteLine(text.Length); } catch (NullReferenceException e) { Console.WriteLine("Object is null."); }
Sample Program
This program asks the user for a number and divides 100 by it. It handles errors if the user enters zero or something that is not a number. The finally block always runs to say thank you.
C Sharp (C#)
using System; class Program { static void Main() { try { Console.WriteLine("Enter a number:"); int number = int.Parse(Console.ReadLine() ?? "0"); int result = 100 / number; Console.WriteLine($"100 divided by {number} is {result}."); } catch (DivideByZeroException) { Console.WriteLine("Error: You cannot divide by zero."); } catch (FormatException) { Console.WriteLine("Error: That is not a valid number."); } finally { Console.WriteLine("Thank you for using the program."); } } }
Important Notes
Always handle exceptions you expect to happen to keep your program friendly.
Use finally to clean up resources like files or connections.
Don't catch exceptions you can't handle properly; let them bubble up if needed.
Summary
Exception handling stops your program from crashing on errors.
It lets you show helpful messages to users when something goes wrong.
Use try, catch, and finally blocks to manage errors safely.
Practice
1. Why do we need exception handling in C# programs?
easy
Solution
Step 1: Understand what happens without exception handling
Without exception handling, errors cause the program to stop immediately, which is called crashing.Step 2: Identify the purpose of exception handling
Exception handling lets the program catch errors and continue running or show helpful messages instead of crashing.Final Answer:
To prevent the program from crashing when an error occurs -> Option BQuick Check:
Exception handling prevents crashes = C [OK]
Hint: Exception handling stops crashes and shows messages [OK]
Common Mistakes:
- Thinking exception handling makes code faster
- Confusing exception handling with code optimization
- Believing exception handling removes the need for variables
2. Which of the following is the correct syntax to start handling exceptions in C#?
easy
Solution
Step 1: Recall the structure of exception handling
In C#, exception handling starts with atryblock followed by one or morecatchblocks.Step 2: Match the correct syntax
try { /* code */ } catch { /* handle error */ } correctly showstry { }followed bycatch { }. Other options have wrong order or invalid keywords.Final Answer:
try { /* code */ } catch { /* handle error */ } -> Option DQuick Check:
try-catch syntax = B [OK]
Hint: Exception handling always starts with try block [OK]
Common Mistakes:
- Putting catch before try
- Using unknown keywords like handle or error
- Missing the try block entirely
3. What will be the output of this C# code?
try {
int x = 10 / 0;
Console.WriteLine("Result: " + x);
} catch (DivideByZeroException) {
Console.WriteLine("Cannot divide by zero.");
}medium
Solution
Step 1: Identify the error in the try block
The code tries to divide 10 by 0, which causes aDivideByZeroException.Step 2: Check the catch block handling
The catch block catchesDivideByZeroExceptionand prints "Cannot divide by zero." instead of crashing.Final Answer:
Cannot divide by zero. -> Option CQuick Check:
Divide by zero caught = D [OK]
Hint: Divide by zero triggers catch block output [OK]
Common Mistakes:
- Expecting program to crash instead of catching error
- Thinking output is 'Result: 0'
- Ignoring the catch block
4. Find the error in this exception handling code:
try {
int[] arr = new int[3];
Console.WriteLine(arr[5]);
} catch (IndexOutOfRangeException e) {
Console.WriteLine("Index error: " + e.Message);
} finally {
Console.WriteLine("Done.");
}medium
Solution
Step 1: Analyze the try block code
The code accesses index 5 of an array with size 3, causing anIndexOutOfRangeException.Step 2: Check the catch and finally blocks
The catch block correctly catchesIndexOutOfRangeExceptionand prints a message. The finally block prints "Done." This is correct usage.Final Answer:
There is no error; code handles exception correctly -> Option AQuick Check:
Correct catch and finally usage = A [OK]
Hint: Catch correct exception type and use finally for cleanup [OK]
Common Mistakes:
- Catching wrong exception type
- Forgetting finally block
- Assuming array size causes error
5. You want to read a number from user input and handle errors if the input is not a number. Which code snippet correctly uses exception handling to do this?
hard
Solution
Step 1: Understand the goal
We want to read a number and catch errors if input is not a valid number.Step 2: Check each option for correct exception handling
try { int num = int.Parse(Console.ReadLine()); Console.WriteLine($"You entered {num}"); } catch (FormatException) { Console.WriteLine("Please enter a valid number."); } usestrywithint.Parseand catchesFormatException, which is correct. int num = int.Parse(Console.ReadLine()); Console.WriteLine($"You entered {num}"); has no error handling. try { int num = Console.ReadLine(); Console.WriteLine($"You entered {num}"); } catch (Exception) { Console.WriteLine("Error occurred."); } tries to assign string to int without parsing. try { int num = Convert.ToInt32(Console.ReadLine()); } finally { Console.WriteLine("Input processed."); } uses finally but no catch, so errors are not handled.Final Answer:
try { int num = int.Parse(Console.ReadLine()); Console.WriteLine($"You entered {num}"); } catch (FormatException) { Console.WriteLine("Please enter a valid number."); } -> Option AQuick Check:
Try-catch with int.Parse and FormatException = A [OK]
Hint: Use try-catch around int.Parse to catch invalid input [OK]
Common Mistakes:
- Not using try-catch for parsing input
- Assigning string directly to int variable
- Using finally without catch to handle errors
