Skip to main content

Types of Exceptions in .NET

The exception is the process that occurred during the run time in the software application, it happens when the developer does not manage the code in the right way or something is not handled properly. an exception is certain types and breaks the application. In this blog, I will show a few types of exceptions, which we face in everyday development, in this blog my focus in.Net C#, as per the language the name may be vary based on the syntax but the type of exception should have the same for all languages


Exceptions Overview

Exceptions have the following properties:

  • to use include exception need to import System.Exception.
  • always use try block around the statements.
  • Once the exception occurs,try block, 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 for an exception in the program, it stops executing with an error message.
  • if you do not write any catch handler then leave the application in a known state. If you catch it, rethrow it using the throw keyword at the end of the catch block, it will pass on it to the next handler.
  • we can add an exception defined variable to obtain more information about the exception that occurred.
  • by using the throw keyword, we can be explicitly generated by a program.

Types of Exception

Here are the details of a few types of exceptions, that exception is not only bound with C#, indeed it comes with every programing language only the syntax is changed

ArgumentException

ArrayTypeMismatchException

ArgumentNullException

ArgumentOutOfRangeException

DivideByZeroException

FileNotFoundException

FormatException

IOException

IndexOutOfRangeException

InvalidOperationException

InvalidCastException

KeyNotFoundException

NotSupportedException

NullReferenceException

OverflowException

OutOfMemoryException

StackOverflowException

TimeoutException

Here is a detailed description of all

ArgumentException

This is the special kind of exception that occurred when the arguments are the data you pass into the method's parameters. it is the actual value of this variable that gets passed to function. if the bed argument passed (e.g., wrong data type) to the method then this exception occurred. to overcome it always pass the argument with the defined data type

ArrayTypeMismatchException

This is a special kind of exception, It occurred when any mismatch happened in the array type.

ArgumentNullException

This is a special kind of exception, It occurred when the null argument is passed to a method.

ArgumentOutOfRangeException              

This is a special kind of exception, It happens if the value of an argument is outside the range of valid values.

DivideByZeroException

This is a special kind of exception, It happened when the Integer value was divided by 0 (Zero)

FileNotFoundException

This is a special kind of exception, This exception occurred if the physical file is not found in the specified location

FormatException            

This is a special kind of exception, This exception occurred when the specific format is not provided, eg., string value parses to int it will occur.


Console.WriteLine("Your current age:");
string lineCode = Console.ReadLine();
try
{
    ageObject = Int32.Parse(lineCode);
}
catch (FormatException)
{
    Console.WriteLine("{0} is not an integer, Kindly check your input"lineCode);  
}

IOException

This is a special kind of exception, It occurred when I/O (Input-Output) related operations happened and if throwing an exception due to some mismatch.

IndexOutOfRangeException            

This is a special kind of exception, It occurred when the index of an array is out of range, eg., 


var arrayObject = new int[3]

The first and last elements in the array are

var firstElement = arrayObject[0];
var lastElement = arrayObject[3];
when we wright the loop like this way

for (int index = 0index <= array.Lengthindex++)
{
    Console.WriteLine(arrayObject[index]);
}

It throws the exception

InvalidOperationException  

This is a special kind of exception, It occurred when the method call is invalid in an object's current state.


bool hasMatch = str.Split(',').Any(x => x.Equals(another));
ViewBag.test = hasMatch ? "Match" : "No Match";

InvalidCastException

This is a special kind of exception, This occurred when the typecasting was not done appropriately for example if 

int convert to string, it throws the exception.

NotSupportedException      

It occurred when a method or operation is not supported.

If isReadOnly can only be set at the time when the object is created (e.g. a constructor argument), and never at any other time, then NotSupportedException should be used

NullReferenceException      

This kind of exception has occurred when the object has a null value.

using System;
class OverflowClass{
   static void Main() {
      string strNull = null;
      strNull.ToUpper();
   }
}

OutOfMemoryException     

This Kind of exception occurred when the application works on a large amount of memory processing and does not get enough memory to execute the code.  means it occurred when the system does not have enough memory space to perform any operation.

one of the examples is: it also happened when you are attempting to expand a StringBuilder object beyond the length defined by its StringBuilder.

OverflowException   

This kind of exception occurred when arithmetic, casting, or conversion operation is performed and results in an overflow. 

one of the examples is., When we set the value to int.Parse() method that is out of integer range will through the Exception, refer below code snippet


using System;
class OverflowEceptionClass{
   static void Main() {
      string str1 = "7538197927390033290";
      int res1 = int.Parse(str1);
   }
}


StackOverflowException

This kind of exception comes when a stack in memory overflows. usually, it happened due to recursive methods call or an infinite loop is running so that it breaks the current operation which is in progress and through the exception.

using System;
class Program
{
    static void RecursiveExample(int valueParameter)
    {
        // this is just comment of Write call number and call this method again.
        // It is the example of The stack will eventually overflow.
        Console.WriteLine(valueParameter);
        RecursiveExample(++valueParameter);
    }
    static void Main()
    {
        // Below function will Begin the infinite recursion.
        RecursiveExample(0);
    }
}

TimeoutException    

It occurred when a  very long process of the operation is taking place in the application and exceed the threshold of the timeout,

In simple words, it comes when the time interval allotted to an operation has expired.

Conclusion

The exception comes in any way and It is clear that the exception breaks the application and it makes a loss of business and clients confidence to overcome this issue, the developer should follow the guidelines of coding and use try-catch properly to handle the exceptions. apart from that developers can create their own custom exception which can handle the exception without defining their type.

Hope it will help!!!

Kindly share your feedback so that I can improve my blogs

Thank you :)



Comments

Popular posts from this blog

Power Apps modern driven app Interview Question and answer

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 the need for extensive coding. These apps can be 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 : Screens serve as the user interface for the app and can include multiple layouts, controls, and data visualizations. Data sources : These are the various repositories where the app can retrieve and store data, such as SharePoint lists, SQL databases, Excel files, etc. Connectors : Connectors enable integration with external services and systems, allowing data to be fetched or updated. Formulas : Power Apps uses a formula language called Power Apps ...

Interview Questions of SPFx SharePoint

What is SPFx? The SharePoint Framework (SPFx) is a web part model that provides full support for client-side SharePoint development, it is easy to integrate with SharePoint data, and extend Microsoft Teams. With the SharePoint Framework, you can use modern web technologies and tools in your preferred development environment to build productive experiences and apps that are responsive and mobile-ready. Scenario Based asking Scenario 1: Scenario: Your team is developing a SharePoint Framework (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 1: How would you approach implementing this functionality in an SPFx web...

SPFX Interview question for 2023

SPFx Interview Questions for 2023 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 the structure of an SPFx solution? Answer: An SPFx solution consists of the following key components: Web Parts: These are the building blocks of SPFx solutions, representing the vi...