{"id":5176,"date":"2024-04-13T19:59:46","date_gmt":"2024-04-13T19:59:46","guid":{"rendered":"https:\/\/reviewnprep.com\/blog\/?p=5176"},"modified":"2024-04-07T20:07:09","modified_gmt":"2024-04-07T20:07:09","slug":"dealing-with-the-unexpected-exception-handling-in-c","status":"publish","type":"post","link":"https:\/\/reviewnprep.com\/blog\/dealing-with-the-unexpected-exception-handling-in-c\/","title":{"rendered":"Dealing With the Unexpected: Exception Handling in C#"},"content":{"rendered":"\n<p>Exception handling is an essential aspect of any robust software development process, ensuring that your application gracefully handles unexpected situations that may arise during runtime. In C#, exception handling allows you to detect, handle, and recover from errors, providing a safety net for your code. <\/p>\n\n\n\n<p>In this blog, we&#8217;ll delve into the importance of exception handling, explore real-world examples of exceptions, and outline best practices along with code examples to handle them effectively in C#. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Exception Handling is Needed?<\/h2>\n\n\n\n<p>In <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/csharp\/\" target=\"_blank\" rel=\"noreferrer noopener\">C#<\/a>, exceptions are objects that represent error conditions or unexpected situations that occur during program execution. When an exception is thrown, it disrupts the normal flow of the program and can potentially cause it to crash or behave unexpectedly. <\/p>\n\n\n\n<p>Imagine you&#8217;re writing a program to calculate someone&#8217;s age based on their birth year. Everything seems smooth until the user enters a nonsensical value like &#8220;abc&#8221; instead of a year. This unexpected input would crash your program without proper handling. This is where exception handling comes in, allowing you to gracefully handle these situations and prevent your application from crashing.<\/p>\n\n\n\n<p>Below are some additional reasons on why exception handling is needed in C#. <\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Maintain Application Stability<\/strong>: By handling exceptions properly, you can prevent your application from crashing and ensure that it behaves in a predictable manner, even in the face of errors.<\/li>\n\n\n\n<li><strong>Error Logging and Debugging<\/strong>: Exception handling allows you to log errors and gather valuable information about the state of the program when an exception occurs, making it easier to debug and fix issues.<\/li>\n\n\n\n<li><strong>Improve User Experience<\/strong>: By gracefully handling exceptions, you can provide informative error messages to users, guiding them on how to resolve issues without causing frustration.<\/li>\n\n\n\n<li><strong>Ensure Data Integrity<\/strong>: Exception handling helps maintain data integrity by handling errors that may occur during data processing or manipulation.<\/li>\n\n\n\n<li><strong>Resource Management<\/strong>: Exceptions can help you manage resources more effectively by ensuring that resources are properly cleaned up, even when errors occur.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Real-World Examples of Exceptions in C#<\/h2>\n\n\n\n<p>Exceptions can occur in a variety of scenarios, such as:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>File I\/O Exceptions<\/strong>: When working with files, exceptions can be thrown if the file doesn&#8217;t exist, can&#8217;t be read or written to, or if there are permissions issues.<\/li>\n\n\n\n<li><strong>Network Exceptions<\/strong>: When communicating over a network, exceptions can be thrown due to connectivity issues, timeouts, or invalid server responses.<\/li>\n\n\n\n<li><strong>Database Exceptions<\/strong>: When interacting with a database, exceptions can occur due to invalid queries, connection issues, or data integrity violations.<\/li>\n\n\n\n<li><strong>Custom Exceptions<\/strong>: Developers can create and throw their own custom exceptions to handle specific error conditions in their applications.<\/li>\n\n\n\n<li><strong>NullReferenceException<\/strong>: Occurs when attempting to access members of a null object reference.<\/li>\n\n\n\n<li><strong>ArgumentException<\/strong>: Raised when one or more arguments passed to a method are invalid.<\/li>\n\n\n\n<li><strong>InvalidOperationException<\/strong>: Signifies an invalid operation in the current state of an object.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Exception Handling<\/h2>\n\n\n\n<p>To ensure that your exception handling is effective and maintainable, follow these best practices:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. Catch Specific Exceptions<\/strong><\/h3>\n\n\n\n<p>Instead of catching the general\u00a0<code>Exception<\/code>\u00a0class, catch specific exception types whenever possible. This makes your code more readable and easier to maintain.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        try\n        {\n            int[] numbers = null;\n            Console.WriteLine(numbers.Length); \/\/ Throws NullReferenceException\n        }\n        catch (NullReferenceException ex)\n        {\n            Console.WriteLine(&quot;NullReferenceException occurred: &quot; + ex.Message);\n            \/\/ Log or handle the exception appropriately\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(&quot;An unexpected error occurred: &quot; + ex.Message);\n            \/\/ Log or handle the exception appropriately\n        }\n    }\n}\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">using<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">System<\/span><span style=\"color: #ADBAC7\">;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">class<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">Program<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">{<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #F47067\">static<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">void<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">Main<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">string<\/span><span style=\"color: #ADBAC7\">[] <\/span><span style=\"color: #F69D50\">args<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">try<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            <\/span><span style=\"color: #F47067\">int<\/span><span style=\"color: #ADBAC7\">[] <\/span><span style=\"color: #F69D50\">numbers<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">null<\/span><span style=\"color: #ADBAC7\">;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(numbers.Length); <\/span><span style=\"color: #768390\">\/\/ Throws NullReferenceException<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">catch<\/span><span style=\"color: #ADBAC7\"> (<\/span><span style=\"color: #F69D50\">NullReferenceException<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">ex<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;NullReferenceException occurred: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> ex.Message);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Log or handle the exception appropriately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">catch<\/span><span style=\"color: #ADBAC7\"> (<\/span><span style=\"color: #F69D50\">Exception<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">ex<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;An unexpected error occurred: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> ex.Message);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Log or handle the exception appropriately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">}<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>In this example, we first try to access the <code>Length<\/code> property of a null array, which will throw a <code>NullReferenceException<\/code>. Instead of catching a general <code>Exception<\/code>, we catch the specific <code>NullReferenceException<\/code>. This makes the code more readable and allows for more targeted exception handling. If there are other exceptions that we haven&#8217;t specifically handled, they will be caught by the general <code>Exception<\/code> catch block for fallback handling.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Implement Proper Exception Hierarchies<\/h3>\n\n\n\n<p>If you&#8217;re creating custom exceptions, create a logical hierarchy that extends from the base\u00a0<code>Exception<\/code>\u00a0class. This will make it easier to catch and handle related exceptions together.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"using System;\n\n\/\/ Base custom exception class\npublic class CustomException : Exception\n{\n    public CustomException(string message) : base(message)\n    {\n    }\n}\n\n\/\/ Custom exception class for file-related errors\npublic class FileNotFoundException : CustomException\n{\n    public FileNotFoundException(string message) : base(message)\n    {\n    }\n}\n\n\/\/ Custom exception class for database-related errors\npublic class DatabaseException : CustomException\n{\n    public DatabaseException(string message) : base(message)\n    {\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        try\n        {\n            \/\/ Simulating a file operation that throws FileNotFoundException\n            throw new FileNotFoundException(&quot;File not found.&quot;);\n        }\n        catch (FileNotFoundException ex)\n        {\n            Console.WriteLine(&quot;FileNotFoundException occurred: &quot; + ex.Message);\n            \/\/ Log or handle the exception appropriately\n        }\n        catch (DatabaseException ex)\n        {\n            Console.WriteLine(&quot;DatabaseException occurred: &quot; + ex.Message);\n            \/\/ Log or handle the exception appropriately\n        }\n        catch (CustomException ex)\n        {\n            Console.WriteLine(&quot;CustomException occurred: &quot; + ex.Message);\n            \/\/ Log or handle the exception appropriately\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(&quot;An unexpected error occurred: &quot; + ex.Message);\n            \/\/ Log or handle the exception appropriately\n        }\n    }\n}\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">using<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">System<\/span><span style=\"color: #ADBAC7\">;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #768390\">\/\/ Base custom exception class<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">public<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">class<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">CustomException<\/span><span style=\"color: #ADBAC7\"> : <\/span><span style=\"color: #F69D50\">Exception<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">{<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #F47067\">public<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">CustomException<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">string<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">message<\/span><span style=\"color: #ADBAC7\">) : <\/span><span style=\"color: #6CB6FF\">base<\/span><span style=\"color: #ADBAC7\">(message)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">}<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #768390\">\/\/ Custom exception class for file-related errors<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">public<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">class<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">FileNotFoundException<\/span><span style=\"color: #ADBAC7\"> : <\/span><span style=\"color: #F69D50\">CustomException<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">{<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #F47067\">public<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">FileNotFoundException<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">string<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">message<\/span><span style=\"color: #ADBAC7\">) : <\/span><span style=\"color: #6CB6FF\">base<\/span><span style=\"color: #ADBAC7\">(message)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">}<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #768390\">\/\/ Custom exception class for database-related errors<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">public<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">class<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">DatabaseException<\/span><span style=\"color: #ADBAC7\"> : <\/span><span style=\"color: #F69D50\">CustomException<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">{<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #F47067\">public<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">DatabaseException<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">string<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">message<\/span><span style=\"color: #ADBAC7\">) : <\/span><span style=\"color: #6CB6FF\">base<\/span><span style=\"color: #ADBAC7\">(message)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">}<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">class<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">Program<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">{<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #F47067\">static<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">void<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">Main<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">string<\/span><span style=\"color: #ADBAC7\">[] <\/span><span style=\"color: #F69D50\">args<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">try<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Simulating a file operation that throws FileNotFoundException<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            <\/span><span style=\"color: #F47067\">throw<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">new<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">FileNotFoundException<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;File not found.&quot;<\/span><span style=\"color: #ADBAC7\">);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">catch<\/span><span style=\"color: #ADBAC7\"> (<\/span><span style=\"color: #F69D50\">FileNotFoundException<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">ex<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;FileNotFoundException occurred: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> ex.Message);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Log or handle the exception appropriately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">catch<\/span><span style=\"color: #ADBAC7\"> (<\/span><span style=\"color: #F69D50\">DatabaseException<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">ex<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;DatabaseException occurred: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> ex.Message);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Log or handle the exception appropriately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">catch<\/span><span style=\"color: #ADBAC7\"> (<\/span><span style=\"color: #F69D50\">CustomException<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">ex<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;CustomException occurred: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> ex.Message);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Log or handle the exception appropriately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">catch<\/span><span style=\"color: #ADBAC7\"> (<\/span><span style=\"color: #F69D50\">Exception<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">ex<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;An unexpected error occurred: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> ex.Message);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Log or handle the exception appropriately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">}<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>In this example, we have a base custom exception class <code>CustomException<\/code> that extends the <code>Exception<\/code> class. We then create two specific exception classes: <code>FileNotFoundException<\/code> for file-related errors and <code>DatabaseException<\/code> for database-related errors. Both of these specific exception classes inherit from <code>CustomException<\/code>, establishing a logical hierarchy.<\/p>\n\n\n\n<p>When handling exceptions in the <code>Main<\/code> method, we catch specific exceptions first (<code>FileNotFoundException<\/code> and <code>DatabaseException<\/code>), followed by the base <code>CustomException<\/code>. Finally, we have a catch block for general exceptions (<code>Exception<\/code>) to handle any unforeseen errors. This hierarchical approach makes it easier to manage related exceptions and handle them appropriately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. <strong>Provide Meaningful Error Messages<\/strong><\/h3>\n\n\n\n<p>When throwing exceptions, provide clear and descriptive error messages that can help with debugging and error handling.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"using System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        try\n        {\n            int result = Divide(10, 0); \/\/ Throws DivideByZeroException\n            Console.WriteLine(&quot;Result: &quot; + result);\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(&quot;An error occurred: &quot; + ex.Message);\n            \/\/ Log or handle the exception appropriately\n        }\n    }\n\n    static int Divide(int dividend, int divisor)\n    {\n        if (divisor == 0)\n        {\n            \/\/ Throw DivideByZeroException with clear error message\n            throw new DivideByZeroException(&quot;Cannot divide by zero. Please provide a non-zero divisor.&quot;);\n        }\n\n        return dividend \/ divisor;\n    }\n}\n\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">using<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">System<\/span><span style=\"color: #ADBAC7\">;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">class<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">Program<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">{<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #F47067\">static<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">void<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">Main<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">string<\/span><span style=\"color: #ADBAC7\">[] <\/span><span style=\"color: #F69D50\">args<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">try<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            <\/span><span style=\"color: #F47067\">int<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">result<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">Divide<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #6CB6FF\">10<\/span><span style=\"color: #ADBAC7\">, <\/span><span style=\"color: #6CB6FF\">0<\/span><span style=\"color: #ADBAC7\">); <\/span><span style=\"color: #768390\">\/\/ Throws DivideByZeroException<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Result: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> result);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">catch<\/span><span style=\"color: #ADBAC7\"> (<\/span><span style=\"color: #F69D50\">Exception<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">ex<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;An error occurred: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> ex.Message);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Log or handle the exception appropriately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    }<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #F47067\">static<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">int<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">Divide<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">int<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">dividend<\/span><span style=\"color: #ADBAC7\">, <\/span><span style=\"color: #F47067\">int<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">divisor<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">if<\/span><span style=\"color: #ADBAC7\"> (divisor <\/span><span style=\"color: #F47067\">==<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">0<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Throw DivideByZeroException with clear error message<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            <\/span><span style=\"color: #F47067\">throw<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">new<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">DivideByZeroException<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Cannot divide by zero. Please provide a non-zero divisor.&quot;<\/span><span style=\"color: #ADBAC7\">);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">return<\/span><span style=\"color: #ADBAC7\"> dividend <\/span><span style=\"color: #F47067\">\/<\/span><span style=\"color: #ADBAC7\"> divisor;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">}<\/span><\/span>\n<span class=\"line\"><\/span><\/code><\/pre><\/div>\n\n\n\n<p>In this example, the <code>Divide<\/code> method attempts to divide two numbers but checks if the divisor is zero before performing the division operation. If the divisor is zero, it throws a <code>DivideByZeroException<\/code> with a clear and descriptive error message: &#8220;Cannot divide by zero. Please provide a non-zero divisor.&#8221;<\/p>\n\n\n\n<p>When catching exceptions in the <code>Main<\/code> method, we print out the error message (<code>ex.Message<\/code>) to the console. This provides clear feedback to the user or developer about the nature of the error that occurred, making it easier to understand and handle the exception appropriately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. <strong>Clean Up Resources<\/strong><\/h3>\n\n\n\n<p>Use the\u00a0<code>try<\/code>\/<code>catch<\/code>\/<code>finally<\/code>\u00a0block to ensure that resources are properly cleaned up, even when exceptions occur. <\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"using System;\nusing System.IO;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        FileStream fileStream = null;\n\n        try\n        {\n            \/\/ Open a file\n            fileStream = File.Open(&quot;example.txt&quot;, FileMode.OpenOrCreate);\n\n            \/\/ Perform file operations (reading, writing, etc.)\n            byte[] buffer = new byte[1024];\n            \/\/ Simulate reading from the file\n            fileStream.Read(buffer, 0, buffer.Length);\n\n            \/\/ Simulate a potential exception\n            \/\/ Uncomment the next line to simulate an exception\n            \/\/ throw new IOException(&quot;Error while processing file&quot;);\n        }\n        catch (IOException ex)\n        {\n            Console.WriteLine(&quot;An IO exception occurred: &quot; + ex.Message);\n            \/\/ Log or handle the exception appropriately\n        }\n        finally\n        {\n            \/\/ Ensure the file stream is properly closed\n            if (fileStream != null)\n            {\n                try\n                {\n                    fileStream.Close();\n                }\n                catch (Exception ex)\n                {\n                    Console.WriteLine(&quot;An error occurred while closing the file: &quot; + ex.Message);\n                    \/\/ Log or handle the exception appropriately\n                }\n            }\n        }\n    }\n}\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">using<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">System<\/span><span style=\"color: #ADBAC7\">;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">using<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">System<\/span><span style=\"color: #ADBAC7\">.<\/span><span style=\"color: #F69D50\">IO<\/span><span style=\"color: #ADBAC7\">;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">class<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">Program<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">{<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #F47067\">static<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">void<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">Main<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">string<\/span><span style=\"color: #ADBAC7\">[] <\/span><span style=\"color: #F69D50\">args<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F69D50\">FileStream<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">fileStream<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">null<\/span><span style=\"color: #ADBAC7\">;<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">try<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Open a file<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            fileStream <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> File.<\/span><span style=\"color: #DCBDFB\">Open<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;example.txt&quot;<\/span><span style=\"color: #ADBAC7\">, FileMode.OpenOrCreate);<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Perform file operations (reading, writing, etc.)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            <\/span><span style=\"color: #F47067\">byte<\/span><span style=\"color: #ADBAC7\">[] <\/span><span style=\"color: #F69D50\">buffer<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">new<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">byte<\/span><span style=\"color: #ADBAC7\">[<\/span><span style=\"color: #6CB6FF\">1024<\/span><span style=\"color: #ADBAC7\">];<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Simulate reading from the file<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            fileStream.<\/span><span style=\"color: #DCBDFB\">Read<\/span><span style=\"color: #ADBAC7\">(buffer, <\/span><span style=\"color: #6CB6FF\">0<\/span><span style=\"color: #ADBAC7\">, buffer.Length);<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Simulate a potential exception<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Uncomment the next line to simulate an exception<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ throw new IOException(&quot;Error while processing file&quot;);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">catch<\/span><span style=\"color: #ADBAC7\"> (<\/span><span style=\"color: #F69D50\">IOException<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">ex<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;An IO exception occurred: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> ex.Message);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Log or handle the exception appropriately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        <\/span><span style=\"color: #F47067\">finally<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">            \/\/ Ensure the file stream is properly closed<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            <\/span><span style=\"color: #F47067\">if<\/span><span style=\"color: #ADBAC7\"> (fileStream <\/span><span style=\"color: #F47067\">!=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">null<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">                <\/span><span style=\"color: #F47067\">try<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">                {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">                    fileStream.<\/span><span style=\"color: #DCBDFB\">Close<\/span><span style=\"color: #ADBAC7\">();<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">                }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">                <\/span><span style=\"color: #F47067\">catch<\/span><span style=\"color: #ADBAC7\"> (<\/span><span style=\"color: #F69D50\">Exception<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">ex<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">                {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">                    Console.<\/span><span style=\"color: #DCBDFB\">WriteLine<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;An error occurred while closing the file: &quot;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">+<\/span><span style=\"color: #ADBAC7\"> ex.Message);<\/span><\/span>\n<span class=\"line\"><span style=\"color: #768390\">                    \/\/ Log or handle the exception appropriately<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">                }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">            }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">        }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    }<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">}<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>In this example, we attempt to open a file <code>\"example.txt\"<\/code> using a <code>FileStream<\/code> within the <code>try<\/code> block. We perform some file operations (reading in this case) and simulate a potential exception (commented out for demonstration).<\/p>\n\n\n\n<p>If an <code>IOException<\/code> occurs during file operations, it is caught in the <code>catch<\/code> block where we log the exception message. Regardless of whether an exception occurs or not, the <code>finally<\/code> block is always executed. Inside the <code>finally<\/code> block, we ensure that the <code>FileStream<\/code> is properly closed to release system resources. This ensures that the file stream is cleaned up, even if an exception occurs during file processing.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Important Things to Consider for Exceptional Handling in C#<\/h2>\n\n\n\n<p><strong>Don&#8217;t Swallow Exceptions<\/strong>: Avoid catching exceptions without properly handling them or at least logging them. This can make it harder to diagnose and fix issues.<\/p>\n\n\n\n<p><strong>Don&#8217;t Use Exceptions for Control Flow<\/strong>: Exceptions should be used for exceptional circumstances, not for controlling the flow of your program.<\/p>\n\n\n\n<p><strong>Consider Performance Implications<\/strong>: While exception handling is essential, excessive use of exceptions can impact performance. Use them judiciously and consider alternative approaches when appropriate.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Final Thoughts<\/h2>\n\n\n\n<p>Exception handling is a critical aspect of writing robust and reliable software in C#. By following best practices and understanding how to effectively handle exceptions, you can create applications that gracefully handle errors and provide a better user experience. <\/p>\n\n\n\n<p>Remember, proper exception handling is not just a nice-to-have feature; it&#8217;s a necessity for building high-quality, maintainable, and reliable applications. <\/p>\n\n\n\n<p>Happy Coding!<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>Further Reading:<\/p>\n\n\n\n<p><a href=\"https:\/\/reviewnprep.com\/blog\/how-can-beginners-learn-coding-and-become-an-expert\/\" target=\"_blank\" rel=\"noreferrer noopener\">How can beginners learn coding and become an expert.<\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/reviewnprep.com\/blog\/the-hidden-power-of-soft-skills-why-coding-alone-wont-cut-it-in-tech-careers\/\" target=\"_blank\" rel=\"noreferrer noopener\">The Hidden Power of Soft Skills: Why Coding Alone Won\u2019t Cut It in Tech Careers<\/a><\/p>\n<\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p>Exception handling is an essential aspect of any robust software development process, ensuring that your application gracefully handles unexpected situations that may arise during runtime. In C#, exception handling allows you to detect, handle, and recover from errors, providing a safety net for your code. In this blog, we&#8217;ll delve into the importance of exception [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":5179,"comment_status":"open","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"footnotes":""},"categories":[253],"tags":[388,323],"class_list":["post-5176","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development","tag-c-3","tag-development"],"_links":{"self":[{"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/posts\/5176"}],"collection":[{"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/comments?post=5176"}],"version-history":[{"count":2,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/posts\/5176\/revisions"}],"predecessor-version":[{"id":5178,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/posts\/5176\/revisions\/5178"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/media\/5179"}],"wp:attachment":[{"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/media?parent=5176"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/categories?post=5176"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/tags?post=5176"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}