Lecture Topics:
try
, catch
, finally
Lab:
Exception handling in .NET allows graceful recovery from runtime errors, ensuring robust applications.
Definition:
Exceptions are objects derived from System.Exception
, thrown when errors occur.
Example:
int Divide(int a, int b)
{
if (b == 0)
throw new DivideByZeroException("Cannot divide by zero");
return a / b;
}
Checked & Unchecked Statements:
Checked: Ensures arithmetic overflow throws an OverflowException
.
Example:
checked
{
int max = int.MaxValue;
Console.WriteLine(max + 1); // Throws OverflowException
}
Unchecked: Ignores overflow, wrapping around (default behavior for most operations).
Example:
unchecked
{
int max = int.MaxValue;
Console.WriteLine(max + 1); // Outputs: -2147483648 (wraps around)
}
Key Points:
checked
is useful for critical calculations; unchecked
is the default in C#.checked(max + 1)
.The try
, catch
, finally
:
try
: Contains code that might throw an exception.
catch
: Handles specific or general exceptions.
finally
: Executes cleanup code, regardless of exception.
Example:
try
{
int result = Divide(10, 0);
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}"); // Outputs: Error: Cannot divide by zero
}
finally
{
Console.WriteLine("Cleanup done");
}
Multiple Catch Blocks:
Handle different exception types, ordered from specific to general.
Example:
try
{
int[] arr = new int[2];
arr[10] = 5; // Throws IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}
Key Points:
catch
without a type catches all exceptions (use sparingly).
finally
is optional but ensures cleanup (e.g., closing files).
C# 6.0+ supports exception filters:
catch (Exception ex) when (ex.Message.Contains("specific"))
{
Console.WriteLine("Filtered exception");
}
Dos & Don'ts of Exception Handling:
Dos:
Catch specific exceptions before general ones.
Use finally
for resource cleanup or implement IDisposable
(Session 5).
Log exceptions for debugging (e.g., using ILogger
in ASP.NET Core).
Throw meaningful exceptions with clear messages.
Example:
try
{
File.ReadAllText("nonexistent.txt");
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File not found: {ex.FileName}");
}
Don'ts:
Don’t catch exceptions you can’t handle.
// Bad practice
try
{
int result = Divide(10, 0);
}
catch (Exception) { } // Swallows exception
Don’t use exceptions for flow control (e.g., instead of if
checks).
Avoid excessive nesting of try
blocks; refactor for clarity.
Don’t throw System.Exception
directly; use specific types.
Why This Matters:
Custom exceptions allow tailored error handling for specific scenarios.