{"id":51,"date":"2014-05-23T07:24:00","date_gmt":"2014-05-23T06:24:00","guid":{"rendered":"https:\/\/debuggersspace.com\/index.php\/2014\/05\/23\/list-down-the-commonly-used-types-of-exceptions-in-net\/"},"modified":"2024-09-28T09:04:46","modified_gmt":"2024-09-28T08:04:46","slug":"list-down-the-commonly-used-types-of-exceptions-in-net","status":"publish","type":"post","link":"https:\/\/debuggersspace.com\/index.php\/2014\/05\/23\/list-down-the-commonly-used-types-of-exceptions-in-net\/","title":{"rendered":"Commonly Used Types of Exceptions in .NET, C#, ASP.NET, .NET Core, and API"},"content":{"rendered":"<div class='booster-block booster-read-block'>\n                <div class=\"twp-read-time\">\n                \t<i class=\"booster-icon twp-clock\"><\/i> <span>Read Time:<\/span>4 Minute, 44 Second                <\/div>\n\n            <\/div><p>Exceptions are critical in C# and .NET for handling errors and ensuring robust application performance. When an error occurs, exceptions provide detailed information that helps identify the issue and manage it gracefully.<\/p>\n<h3>Commonly Used Exceptions in .NET:<\/h3>\n<ul>\n<li><strong>System.Exception<\/strong>: The base class for all exceptions in C#. Any custom exception must inherit from this.<\/li>\n<li><strong>ArgumentNullException<\/strong>: Thrown when a <code>null<\/code> reference is passed to a method that does not accept it.<\/li>\n<li><strong>ArgumentOutOfRangeException<\/strong>: Thrown when the value passed to a method is outside the valid range.<\/li>\n<li><strong>NullReferenceException<\/strong>: Thrown when trying to use an object reference that is <code>null<\/code>.<\/li>\n<li><strong>IndexOutOfRangeException<\/strong>: Thrown when an attempt is made to access an index in an array or collection that is out of bounds.<\/li>\n<li><strong>DivideByZeroException<\/strong>: Thrown when there\u2019s an attempt to divide by zero.<\/li>\n<li><strong>FileNotFoundException<\/strong>: Thrown when a file is not found.<\/li>\n<li><strong>InvalidOperationException<\/strong>: Thrown when a method call is invalid for the current state of the object.<\/li>\n<li><strong>NotImplementedException<\/strong>: Thrown when a requested method or operation is not implemented.<\/li>\n<li><strong>FormatException<\/strong>: Thrown when a format is invalid, like trying to parse a string as an integer.<\/li>\n<li><strong>HttpRequestException<\/strong>: Common in APIs, thrown when there is an issue with an HTTP request.<\/li>\n<li><strong>TaskCanceledException<\/strong>: Thrown when an asynchronous operation is canceled.<\/li>\n<li><strong>UnauthorizedAccessException<\/strong>: Thrown when access to a resource is denied.<\/li>\n<li><strong>TimeoutException<\/strong>: Thrown when an operation exceeds its allotted time to complete.<\/li>\n<\/ul>\n<h3>Real-World Analogy for Exceptions<\/h3>\n<p>Think of exceptions as <strong>traffic lights<\/strong> on a road:<\/p>\n<ul>\n<li><strong>Green light<\/strong>: Everything is normal, traffic flows (program runs smoothly).<\/li>\n<li><strong>Yellow light<\/strong>: Caution! There might be a potential problem ahead (an issue is detected, but the program can handle it).<\/li>\n<li><strong>Red light<\/strong>: Stop! Something is wrong (an exception occurs, halting the program until it&#8217;s resolved).<\/li>\n<\/ul>\n<p>Exceptions act like the red light, stopping the execution until the issue is addressed. Using try-catch blocks ensures the program handles these &#8220;traffic light&#8221; errors effectively.<\/p>\n<h3>Tricky and Important Q&amp;A<\/h3>\n<h4>Q1: What is the difference between <code>NullReferenceException<\/code> and <code>ArgumentNullException<\/code>?<\/h4>\n<p><strong>Answer<\/strong>:<\/p>\n<ul>\n<li><code>NullReferenceException<\/code> occurs when trying to access members of an object that is <code>null<\/code>.<\/li>\n<li><code>ArgumentNullException<\/code> occurs when a method receives <code>null<\/code> as an argument where <code>null<\/code> is not valid.<\/li>\n<\/ul>\n<h4>Q2: Can you throw an exception inside a <code>finally<\/code> block?<\/h4>\n<p><strong>Answer<\/strong>: Yes, but it&#8217;s discouraged. If an exception is thrown inside a <code>finally<\/code> block, it may override any exception thrown in the <code>try<\/code> or <code>catch<\/code> block, making debugging difficult.<\/p>\n<h4>Q3: What\u2019s the best way to handle exceptions in an API?<\/h4>\n<p><strong>Answer<\/strong>: In an API, use global exception handling middleware to catch all unhandled exceptions and return proper HTTP status codes, such as <code>500 Internal Server Error<\/code>, with detailed error messages.<\/p>\n<h4>Q4: Why is catching generic exceptions (<code>catch(Exception ex)<\/code>) discouraged?<\/h4>\n<p><strong>Answer<\/strong>: Catching generic exceptions can hide bugs or unintended exceptions, making it harder to identify the root cause. It&#8217;s better to catch specific exceptions.<\/p>\n<h3>Example of Handling Exceptions in .NET<\/h3>\n<pre><code>\r\npublic class Program {\r\n    public static void Main() {\r\n        try {\r\n            int[] numbers = { 1, 2, 3 };\r\n            Console.WriteLine(numbers[5]);  \/\/ This will throw an IndexOutOfRangeException\r\n        }\r\n        catch (IndexOutOfRangeException ex) {\r\n            Console.WriteLine($\"Index error: {ex.Message}\");\r\n        }\r\n        catch (Exception ex) {\r\n            Console.WriteLine($\"An error occurred: {ex.Message}\");\r\n        }\r\n        finally {\r\n            Console.WriteLine(\"Cleaning up resources...\");\r\n        }\r\n    }\r\n}\r\n<\/code><\/pre>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li><strong>try<\/strong> block: Code that may throw an exception.<\/li>\n<li><strong>catch<\/strong> block: Handles specific exceptions, in this case, <code>IndexOutOfRangeException<\/code>.<\/li>\n<li><strong>finally<\/strong> block: Executes regardless of whether an exception occurs, typically used for cleanup.<\/li>\n<\/ul>\n<h3>How Exceptions Work with OOP Concepts<\/h3>\n<p>Exceptions are tightly integrated into <strong>object-oriented programming (OOP)<\/strong> principles:<\/p>\n<ul>\n<li><strong>Encapsulation<\/strong>: By throwing exceptions when something goes wrong, classes protect their internal state from becoming invalid.<\/li>\n<li><strong>Inheritance<\/strong>: Custom exceptions can inherit from the base <code>System.Exception<\/code> class, allowing developers to create specific exceptions tailored to their needs.<\/li>\n<li><strong>Polymorphism<\/strong>: Multiple <code>catch<\/code> blocks can handle different types of exceptions, offering flexibility in error handling.<\/li>\n<\/ul>\n<h4>Example of Custom Exception Inheritance:<\/h4>\n<pre><code>\r\npublic class InsufficientFundsException : Exception {\r\n    public InsufficientFundsException(string message) : base(message) { }\r\n}\r\n\r\npublic class BankAccount {\r\n    public decimal Balance { get; private set; }\r\n\r\n    public void Withdraw(decimal amount) {\r\n        if (amount &gt; Balance) {\r\n            throw new InsufficientFundsException(\"Not enough balance.\");\r\n        }\r\n        Balance -= amount;\r\n    }\r\n}\r\n\r\npublic class Program {\r\n    public static void Main() {\r\n        BankAccount account = new BankAccount();\r\n        try {\r\n            account.Withdraw(500);  \/\/ Throws custom InsufficientFundsException\r\n        }\r\n        catch (InsufficientFundsException ex) {\r\n            Console.WriteLine(ex.Message);\r\n        }\r\n    }\r\n}\r\n<\/code><\/pre>\n<h3>Benefits of Handling Exceptions<\/h3>\n<ul>\n<li><strong>Graceful Error Handling<\/strong>: Prevents the application from crashing abruptly and allows it to recover from certain errors.<\/li>\n<li><strong>Detailed Error Reporting<\/strong>: Exceptions provide detailed error messages and stack traces that help in debugging.<\/li>\n<li><strong>Cleaner Code<\/strong>: Using exceptions leads to cleaner, more maintainable code compared to relying on error codes or return values.<\/li>\n<li><strong>Improved User Experience<\/strong>: By handling exceptions properly, applications can display user-friendly error messages rather than cryptic system errors.<\/li>\n<\/ul>\n<h3>Code Snippet Using Try-Catch for an API Example<\/h3>\n<p>In an ASP.NET Core API, we can use exception handling middleware to catch and process all exceptions globally:<\/p>\n<pre><code>\r\npublic class Startup {\r\n    public void Configure(IApplicationBuilder app) {\r\n        app.UseExceptionHandler(\"\/error\");\r\n\r\n        app.Use(async (context, next) =&gt; {\r\n            try {\r\n                await next();\r\n            }\r\n            catch (Exception ex) {\r\n                Console.WriteLine($\"Exception caught: {ex.Message}\");\r\n                context.Response.StatusCode = 500;\r\n                await context.Response.WriteAsync(\"An unexpected error occurred.\");\r\n            }\r\n        });\r\n    }\r\n}\r\n<\/code><\/pre>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li><strong>Global Error Handling<\/strong>: The API handles exceptions globally, logging the error and returning a <code>500 Internal Server Error<\/code> response to the client.<\/li>\n<li><strong>User-Friendly Error Messages<\/strong>: The response contains a simplified message for the user while the actual error is logged for developers to troubleshoot.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>In .NET, C#, ASP.NET, and .NET Core, handling exceptions is essential for building robust, error-resistant applications. Common exceptions like <code>NullReferenceException<\/code>, <code>IndexOutOfRangeException<\/code>, and <code>HttpRequestException<\/code> allow developers to pinpoint issues and handle them gracefully. Exceptions play a vital role in implementing OOP principles like encapsulation, inheritance, and polymorphism, while global error handling in APIs ensures a smoother experience for users. Understanding and properly handling exceptions can improve code quality, maintainability, and user experience.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Exceptions are critical in C# and .NET for handling errors and ensuring robust application performance. When an error occurs, exceptions provide detailed information that helps identify the issue and manage it gracefully. Commonly Used Exceptions in .NET: System.Exception: The base class for all exceptions in C#. Any custom exception must inherit from this. ArgumentNullException: Thrown [&hellip;]<\/p>\n","protected":false},"author":43,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","footnotes":""},"categories":[15,146,23,24,20,188,161,148],"tags":[203,204,202],"class_list":["post-51","post","type-post","status-publish","format-standard","hentry","category-net-core-3-1","category-net-interview-qa","category-asp-net","category-c-net","category-oops","category-technical-explorations","category-top-100-qa","category-webapi","tag-exceptions","tag-oops","tag-trycatchblock"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Himanshu Namdeo","author_link":"https:\/\/debuggersspace.com\/author\/admin\/"},"uagb_comment_info":0,"uagb_excerpt":"Exceptions are critical in C# and .NET for handling errors and ensuring robust application performance. When an error occurs, exceptions provide detailed information that helps identify the issue and manage it gracefully. Commonly Used Exceptions in .NET: System.Exception: The base class for all exceptions in C#. Any custom exception must inherit from this. ArgumentNullException: Thrown&hellip;","_links":{"self":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/51"}],"collection":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/users\/43"}],"replies":[{"embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/comments?post=51"}],"version-history":[{"count":2,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/51\/revisions"}],"predecessor-version":[{"id":819,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/posts\/51\/revisions\/819"}],"wp:attachment":[{"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/media?parent=51"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/categories?post=51"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/debuggersspace.com\/index.php\/wp-json\/wp\/v2\/tags?post=51"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}