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

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

Interview Question of Advanced SharePoint SPFx

1. What is WebPack? A module bundling system built on top of Node. js framework is known as a WebPack. It is capable to handle the combination and minification of JavaScript and CSS files, also other files such as images by using plugins. WebPack is the recommended way of bundling the files in JS framework and .Net frameworks. In the SPFx it is used with React Js. 2. What is PowerShell.? PowerShell is a platform introduced by Microsoft to perform cross-platform task automation and configuration management framework, it is made up of a command-line shell, a scripting language. it can be run on Windows, Linux, and macOS. 3. What is bundling and Minification? The terms bundling and minification are the processes of code compressing, which is used to improve the load and request time, It is used in modern JavaScript frameworks and .Net frameworks. It improves the load time by reducing the number of requests to the s

Top20 - SharePoint Framework (SPFx) Interview Questions

1.  Which tool we can use to generate a SharePoint Framework (SPFx) solution? Developers can use  Yeoman to generate SharePoint Framework (SPFx) solution, it is a client-side scaffolding open-source tool to help in web-based development. 2. How developer can ensure that the solution deployed was immediately available to all site collections in SPFx?  To ensure the availability of the deployed solution on all the site collections developer has to configure  skipFeatureDeployment: true  in package-solution.json {     "solution" : {       "name" : "theultimateresources-deployment-client-side-solution" ,       "id" : "as3feca4-4j89-47f1-a0e2-78de8890e5hy" ,       "version" : "2.0.0.0" ,       "skipFeatureDeployment" : true     },     "paths" : {       "zippedPackage" : "solution/theultimateresources-deploy-true.sppkg"     }  }