try/catch/finally, throw new vs rethrow
Use try/catch/finally for predictable error handling; understand throw new vs rethrow; keep examples small and focused.
Exceptions overview
Goal: Handle and propagate errors safely.
- try/catch: handle specific exceptions
- finally: always runs for cleanup
- throw new vs rethrow
- Keep handlers short; do not hide bugs
Specific catch
Catch the most specific exception you expect; keep the handler short and clear.
using System;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Start");
try
{
int x = 10;
int y = 0; // will cause DivideByZeroException
Console.WriteLine(x / y);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero: " + ex.GetType().Name);
}
Console.WriteLine("Continue");
}
}
All lessons in this course
- try/catch/finally, throw new vs rethrow
- Custom exceptions; error design
- IDisposable, using statement