Types of Exceptions in .NET C#
By Vishal Thakur
Introduction
An exception is an issue that occurs during the runtime of a software application. It typically happens when the developer does not manage the code properly or fails to handle certain scenarios. Exceptions can break the application if not handled correctly. In this blog, we will explore various types of exceptions in .NET C# and how to handle them.
Exceptions Overview
Exceptions in .NET have the following properties:
- To use exceptions, you need to import
System.Exception
. - Always use a
try
block around the statements that might throw an exception. - When an exception occurs, the flow of control jumps to the associated exception handler. In C#, the
catch
keyword is used to define an exception handler. - If an exception handler is not defined, the program stops executing with an error message.
- If you catch an exception, you can rethrow it using the
throw
keyword at the end of thecatch
block to pass it to the next handler. - You can add an exception-defined variable to obtain more information about the exception.
- Exceptions can be explicitly generated using the
throw
keyword.
Types of Exceptions
Here are some common types of exceptions in .NET C#:
- ArgumentException: Occurs when an invalid argument is passed to a method.
- ArrayTypeMismatchException: Occurs when there is a mismatch in the array type.
- ArgumentNullException: Occurs when a null argument is passed to a method.
- ArgumentOutOfRangeException: Occurs when the value of an argument is outside the valid range.
- DivideByZeroException: Occurs when an integer value is divided by zero.
- FileNotFoundException: Occurs when a file is not found in the specified location.
- FormatException: Occurs when the format of an argument is invalid.
- IOException: Occurs during input/output operations.
- IndexOutOfRangeException: Occurs when an array index is out of range.
- InvalidOperationException: Occurs when a method call is invalid in the object's current state.
- InvalidCastException: Occurs when typecasting is not done appropriately.
- KeyNotFoundException: Occurs when a key is not found in a collection.
- NotSupportedException: Occurs when a method or operation is not supported.
- NullReferenceException: Occurs when an object has a null value.
- OverflowException: Occurs when an arithmetic operation results in an overflow.
- OutOfMemoryException: Occurs when the system does not have enough memory to perform an operation.
- StackOverflowException: Occurs when the stack in memory overflows, usually due to recursive method calls or infinite loops.
- TimeoutException: Occurs when an operation exceeds the allotted time interval.
Detailed Explanation of Exceptions
ArgumentException
This exception occurs when an invalid argument is passed to a method. For example, if a method expects an integer but receives a string, this exception will be thrown.
ArrayTypeMismatchException
This exception occurs when there is a mismatch in the array type. For example, if you try to store a string in an integer array, this exception will be thrown.
ArgumentNullException
This exception occurs when a null argument is passed to a method that does not accept null values.
ArgumentOutOfRangeException
This exception occurs when the value of an argument is outside the valid range. For example, if a method expects a value between 1 and 10 but receives 15, this exception will be thrown.
DivideByZeroException
This exception occurs when an integer value is divided by zero. For example:
int result = 10 / 0; // This will throw a DivideByZeroException
FileNotFoundException
This exception occurs when a file is not found in the specified location. For example:
string filePath = "C:\\nonexistentfile.txt";
if (!File.Exists(filePath))
{
throw new FileNotFoundException("File not found", filePath);
}
FormatException
This exception occurs when the format of an argument is invalid. For example, if you try to parse a string that is not a valid integer, this exception will be thrown.
string input = "abc";
int number = int.Parse(input); // This will throw a FormatException
IOException
This exception occurs during input/output operations, such as reading or writing to a file. For example:
try
{
File.ReadAllText("C:\\nonexistentfile.txt");
}
catch (IOException ex)
{
Console.WriteLine("An I/O error occurred: " + ex.Message);
}
IndexOutOfRangeException
This exception occurs when an array index is out of range. For example:
int[] numbers = { 1, 2, 3 };
int value = numbers[5]; // This will throw an IndexOutOfRangeException
InvalidOperationException
This exception occurs when a method call is invalid in the object's current state. For example, if you try to modify a collection while iterating over it, this exception will be thrown.
InvalidCastException
This exception occurs when typecasting is not done appropriately. For example:
object obj = "abc";
int number = (int)obj; // This will throw an InvalidCastException
NotSupportedException
This exception occurs when a method or operation is not supported. For example, if you try to modify a read-only collection, this exception will be thrown.
NullReferenceException
This exception occurs when an object has a null value. For example:
string str = null;
int length = str.Length; // This will throw a NullReferenceException
OutOfMemoryException
This exception occurs when the system does not have enough memory to perform an operation. For example, if you try to allocate a large amount of memory, this exception will be thrown.
OverflowException
This exception occurs when an arithmetic operation results in an overflow. For example:
int maxValue = int.MaxValue;
int result = maxValue + 1; // This will throw an OverflowException
StackOverflowException
This exception occurs when the stack in memory overflows, usually due to recursive method calls or infinite loops. For example:
void RecursiveMethod()
{
RecursiveMethod(); // This will eventually throw a StackOverflowException
}
TimeoutException
This exception occurs when an operation exceeds the allotted time interval. For example, if a network request takes too long, this exception will be thrown.
Conclusion
Exceptions are a critical part of software development. They can break the application and lead to a loss of business and client confidence. To avoid this, developers should follow coding best practices and use try-catch blocks to handle exceptions properly. Additionally, developers can create custom exceptions to handle specific scenarios.
I hope this guide helps you understand the different types of exceptions in .NET C#. Please share your feedback so that I can improve my blogs. Thank you! :)
Comments
Post a Comment