Letβs dig into exceptions you can use in a try-catch in C#.
π 1. General Rule
In C#, you can catch any type that derives from System.Exception.
-
The base class:
Exception -
Specialized exceptions:
ArgumentNullException,InvalidOperationException, etc.
You cannot catch things like string or int β only Exception objects.
π 2. Common Exception Types in C#
Here are the most frequently used ones:
General purpose
-
Exceptionβ base type (catches everything, but usually avoided by itself) -
SystemExceptionβ base for system-generated exceptions
Argument / parameter issues
-
ArgumentExceptionβ invalid argument -
ArgumentNullExceptionβ argument isnullwhen it shouldnβt be -
ArgumentOutOfRangeExceptionβ argument not in allowed range
Invalid operations
-
InvalidOperationExceptionβ method call not valid for current state -
NotImplementedExceptionβ feature/method not yet implemented -
NotSupportedExceptionβ method/property not supported
I/O and external issues
-
IOExceptionβ general I/O errors -
FileNotFoundExceptionβ file missing -
DirectoryNotFoundExceptionβ directory missing -
UnauthorizedAccessExceptionβ no permission
Collections / indexing
-
IndexOutOfRangeExceptionβ index outside array bounds -
KeyNotFoundExceptionβ dictionary key doesnβt exist
Type conversion / casting
-
InvalidCastExceptionβ invalid type conversion -
FormatExceptionβ string not in correct format -
OverflowExceptionβ arithmetic overflow
Concurrency / threading
-
ThreadAbortExceptionβ thread forced to stop -
TaskCanceledExceptionβ async task canceled -
OperationCanceledExceptionβ operation canceled (withCancellationToken)
π 3. Example try-catch
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // throws IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index was out of bounds: " + ex.Message);
}
catch (Exception ex)
{
// fallback: catches all other exceptions
Console.WriteLine("Something went wrong: " + ex.Message);
}π 4. Best Practices
-
Catch specific exceptions first, then
Exceptionlast as a fallback. -
Avoid catching
Exceptionunless you need a global safety net. -
Use
finallyfor cleanup (closing files, releasing resources).
β
In short: You can catch any class derived from System.Exception, and C# provides many built-in exceptions for common error scenarios.