21. Exception Handling in C#
Level: Beginner
- What an exception is
- Use
tryandcatch - Use
finally - Throw your own exception
- Handle invalid user input
- Avoid common exception mistakes
An exception is an error that happens while the program is running.
Example:
int marks = int.Parse("abc");
This fails because "abc" cannot become a number.
The Problem: Program Can Crash
In a School Management System, users may enter bad data:
- Marks as
abc - Percentage as
150 - Empty student name
- Missing dictionary key
- Invalid file path
Without handling, the program may stop suddenly.
Exception handling lets us show a useful message and continue safely.
Quick Definitions
- Exception - Runtime error that happens while program is running
- try - Block holding code that might fail
- catch - Block handling the error if it happens
- finally - Block that always runs (cleanup)
- throw - Create and send an exception
- FormatException - Text cannot convert to number
- DivideByZeroException - Dividing by zero
- NullReferenceException - Using object that is null
- ArgumentException - Invalid method argument
- TryParse - Safe way to convert text (returns true/false, no exception)
try and catch
Put risky code inside try.
Handle the error inside catch.
try
{
int marks = int.Parse("abc");
Console.WriteLine(marks);
}
catch (FormatException)
{
Console.WriteLine("Invalid marks. Please enter a number.");
}
finally
finally runs whether there is an error or not.
try
{
Console.WriteLine("Saving marks...");
}
catch (Exception)
{
Console.WriteLine("Something went wrong.");
}
finally
{
Console.WriteLine("Operation completed.");
}
Use finally for cleanup.
Common Exception Types
| Exception | Happens When |
|---|---|
FormatException | Bad text format, like int.Parse("abc") |
DivideByZeroException | Dividing by zero |
NullReferenceException | Accessing object that is null |
ArgumentException | Invalid method argument |
ArgumentOutOfRangeException | Value outside allowed range |
KeyNotFoundException | Dictionary key missing |
Throwing an Exception
You can throw an exception when data is invalid.
static void SaveMarks(int marks)
{
if (marks < 0 || marks > 100)
{
throw new ArgumentOutOfRangeException(nameof(marks), "Marks must be between 0 and 100.");
}
Console.WriteLine($"Marks saved: {marks}");
}
Call it:
try
{
SaveMarks(150);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
}
Prefer TryParse for User Input
For normal user input, do not use exceptions if avoidable.
Better:
string input = "85";
if (int.TryParse(input, out int marks))
{
Console.WriteLine($"Marks: {marks}");
}
else
{
Console.WriteLine("Invalid marks.");
}
Use TryParse because invalid input is common.
Full Example: Safe Marks Entry
When You'll Use This in SMS
Every SMS feature needs exception handling.
Real scenarios:
// User enters marks as "abc"
try { int marks = int.Parse(userInput); }
catch (FormatException) { show "Please enter a number"; }
// Teacher enters percentage > 100
if (percentage > 100) { throw new ArgumentException("Max is 100"); }
// Student marks missing (null)
if (studentMarks == null) { throw new NullReferenceException("No marks found"); }
// Divide by zero when calculating average
try { double avg = total / count; }
catch (DivideByZeroException) { show "No marks to average"; }
// File missing when generating report
try { File.ReadAllText(filePath); }
catch (FileNotFoundException) { show "Report template missing"; }
Real impact:
- Without handling: one bad entry crashes entire SMS
- With handling: show error, let user fix, continue working
- Production SMS catches 100+ error types daily
Best practice: Validate early (check bounds), use TryParse for user input, throw specific exceptions for business rules.
Try This Now
Run the safe marks entry example above. Then experiment:
- Try entering negative marks (should throw)
- Try entering marks > 100 (should throw)
- Enter valid marks (should work)
- Modify to use
TryParseinstead ofParse - Add multiple catch blocks for different exceptions
- Test
finallyblock runs in all cases
See how exception handling prevents crashes.
Exception handling explained: try, catch, finally, throw, Parse vs TryParse, common mistakes. Video coming soon. Subscribe to NexCoding YouTube for updates.
Common Mistakes
Mistake 1: Empty catch
Wrong:
try
{
}
catch
{
}
This hides errors.
Mistake 2: Catching everything first
Catch specific exceptions first, generic Exception last.
Mistake 3: Using exception for normal input
Use TryParse for user input.
Mistake 4: Throwing unclear messages
Give clear messages like Marks must be between 0 and 100.
Best Practices
- Validate input early.
- Catch specific exceptions first.
- Do not use empty catch blocks.
- Use
TryParsefor user input. - Use
finallyfor cleanup. - Include useful error messages.
- Do not hide unexpected errors silently.
Practice Task
Create a method CalculatePercentage(int totalMarks, int maxMarks).
Rules:
- If
maxMarksis 0, throwArgumentException. - If
totalMarksis negative, throwArgumentException. - Otherwise return percentage.
Quick Revision
| Question | Answer |
|---|---|
| What is exception? | Runtime error |
| What does try do? | Holds risky code |
| What does catch do? | Handles error |
| What does finally do? | Always runs |
| What is throw? | Creates an exception |
| Safer than Parse? | TryParse |
Exception handling is a way to handle runtime errors using try, catch, and finally.
finally is used for cleanup code. It runs whether an exception happens or not.
Parse throws an exception for invalid input. TryParse returns true or false safely.
It hides errors and makes debugging difficult.
Throw an exception when invalid data should not be accepted, such as marks outside 0 to 100.
Use ChatGPT, Claude, or Copilot to go deeper on C# exception handling. Try these prompts:
"Explain try, catch, finally with school examples""Give me 5 practice tasks for exception handling""Explain Parse vs TryParse simply""Quiz me with 5 beginner questions about exceptions"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.