Skip to main content

21. Exception Handling in C#

Level: Beginner

ℹ️ What You'll Learn
  • What an exception is
  • Use try and catch
  • 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

ExceptionHappens When
FormatExceptionBad text format, like int.Parse("abc")
DivideByZeroExceptionDividing by zero
NullReferenceExceptionAccessing object that is null
ArgumentExceptionInvalid method argument
ArgumentOutOfRangeExceptionValue outside allowed range
KeyNotFoundExceptionDictionary 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

💻 Try It — Console App
💡 Paste into Program.cs and press F5⌥ GitHub
try
{
SaveStudentMarks("Sahasra Kumar", 92);
SaveStudentMarks("Priya Sharma", 150);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Validation error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
Console.WriteLine("Marks entry completed.");
}

static void SaveStudentMarks(string studentName, int marks)
{
if (string.IsNullOrWhiteSpace(studentName))
{
throw new ArgumentException("Student name is required.");
}

if (marks < 0 || marks > 100)
{
throw new ArgumentOutOfRangeException(nameof(marks), "Marks must be between 0 and 100.");
}

Console.WriteLine($"{studentName}: {marks} marks saved.");
}

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:

  1. Try entering negative marks (should throw)
  2. Try entering marks > 100 (should throw)
  3. Enter valid marks (should work)
  4. Modify to use TryParse instead of Parse
  5. Add multiple catch blocks for different exceptions
  6. Test finally block runs in all cases

See how exception handling prevents crashes.


ℹ️ Video Tutorial

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

  1. Validate input early.
  2. Catch specific exceptions first.
  3. Do not use empty catch blocks.
  4. Use TryParse for user input.
  5. Use finally for cleanup.
  6. Include useful error messages.
  7. Do not hide unexpected errors silently.

Practice Task

Create a method CalculatePercentage(int totalMarks, int maxMarks).

Rules:

  • If maxMarks is 0, throw ArgumentException.
  • If totalMarks is negative, throw ArgumentException.
  • Otherwise return percentage.

Quick Revision

QuestionAnswer
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

🎯 Q1: What is exception handling?

Exception handling is a way to handle runtime errors using try, catch, and finally.

🎯 Q2: What is finally used for?

finally is used for cleanup code. It runs whether an exception happens or not.

🎯 Q3: Difference between Parse and TryParse?

Parse throws an exception for invalid input. TryParse returns true or false safely.

🎯 Q4: Why avoid empty catch?

It hides errors and makes debugging difficult.

🎯 Q5: When should we throw an exception?

Throw an exception when invalid data should not be accepted, such as marks outside 0 to 100.


🤖Use AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

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.

Next Article

File I/O ->

nexcoding.in