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 isnull
when 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
Exception
last as a fallback. -
Avoid catching
Exception
unless you need a global safety net. -
Use
finally
for 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.