Skip to main content

Types of Exceptions in .NET

Types of Exceptions in .NET C#

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 the catch 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! :)

Related Articles

Comments

Popular posts from this blog

Power Apps modern driven app Interview Question and answer

Power Apps Modern Driven App: Questions and Answers Power Apps Modern Driven App: Questions and Answers Power Apps modern driven apps are low-code/no-code platforms that enable users to create custom applications. Below are some common questions and detailed answers to help you understand their capabilities and applications. Question 1: What is a Power Apps modern driven app? Answer: A Power Apps modern driven app is a low-code/no-code application development platform provided by Microsoft. It allows users to create custom applications that can run on various devices and platforms without extensive coding. These apps are built using a visual interface and can integrate with different data sources. Question 2: What are the key components of a Power Apps modern driven app? Answer: The key components of a Power Apps modern driven app are: Screens: Serve as the user interface for the app, including layouts, ...

SPFX Interview question for 2023

SPFx Interview Questions for 2023 SPFx Interview Questions for 2023 Author: Vishal Thakur Question 1: What is SharePoint Framework (SPFx)? Answer: SharePoint Framework (SPFx) is a development model introduced by Microsoft for creating client-side web parts and extensions for SharePoint Online and SharePoint 2019. It is based on modern web technologies like JavaScript, TypeScript, and React, providing a rich and responsive user experience. Question 2: What are the key advantages of using SPFx for SharePoint development? Answer: SPFx offers several advantages, such as: Responsive and mobile-ready web parts and extensions. Seamless integration with SharePoint data and services. Support for modern web development practices and tools. Easy deployment and hosting options. Enhanced security and isolation through the SharePoint app model. Question 3: Can you explain ...

Interview Questions of SPFx SharePoint

SPFx Interview Questions and Scenarios SPFx Interview Questions and Scenarios By Vishal Thakur What is SPFx? The SharePoint Framework (SPFx) is a web part model that provides full support for client-side SharePoint development. It integrates seamlessly with SharePoint data and extends Microsoft Teams. SPFx allows developers to use modern web technologies and tools in their preferred development environment to build responsive and mobile-ready experiences. Scenario-Based Questions Scenario 1: External API Integration Scenario: Your team is developing an SPFx web part that needs to retrieve data from an external API and display it on a SharePoint site. The API requires authentication using OAuth 2.0. The web part should also allow users to refresh the data manually. Question: How woul...