Programs sometimes encounter errors (exceptions). C# gives you tools to handle them safely.
⚠️ What is an Exception?
An error that stops your program, like dividing by zero or reading a missing file.
1
2
int x = 5, y = 0;
int result = x / y; // Throws exception!
🛑 Try/Catch
Catch (handle) exceptions so your program doesn’t crash.
1
2
3
4
5
6
7
8
try
{
int n = int.Parse("hello"); // Error!
}
catch (FormatException)
{
Console.WriteLine("Not a valid number.");
}
📝 General Pattern
1
2
3
4
5
6
7
8
try
{
// Code that might fail
}
catch (ExceptionType ex)
{
// What to do if it fails
}
💡 Try It!
Ask for a number and handle invalid input:
1
2
3
4
5
6
7
8
9
10
Console.Write("Enter a number: ");
try
{
int n = int.Parse(Console.ReadLine());
Console.WriteLine($"You entered {n}");
}
catch
{
Console.WriteLine("Not a valid number!");
}
Next: Try, catch, and finally blocks in detail!