Skip to main content

C# Try Catch & Finally Demystified

One can wonder what can be there to demystify the try catch and finally block,

There are some tricky scenarios in this area

Lets see what are all that:

Ideally Try is used along with Catch, so if any exception arises then it will be get catch in the catch block and based on the  business's preference he / she may want to throw using throw keyword or write in log file or do any other action.

The Try Catch Finally works in the following mannaer


Step 1: Control Comes inside the try block.
Step 2: If the code inside the try executes normal then the control goes to finally block.
Step 3: If the code inside the try is throwing error then it will execute the contents of the catch and then go to finally block.
Step 4: In finally block thw CLR will free up the resources used in that try block.
Step 5: If the function returns the control inside the try block, then also the control will finally comes to finally.
Step 6: You cannot return the control from a finally block, if you do so you will get an compiler error as "Control cannot leave the body of a finally clause".
          
Example 1: Normal Try Catch and Finally block

     static void Main(string[] args)
        {
            string ReturnValue = GetValueFromMethod();
            Console.WriteLine(ReturnValue.ToString());
            Console.ReadLine();
        }
        private static string GetValueFromMethod()
        {
            string ReturnValue = "Initial Value";
            try
            {
                int DividedByValue = 0;
                return ReturnValue;
            }
            catch (Exception Ex)
            {
                // throw Ex;
                return "Catch Value";
            }
            finally
            {
                // The memory will be get cleared here
                ReturnValue = "Finally Value";
            }
        }


Output:

Initial Value

Lets go little deeper by introducing an error

Example 2:

        static void Main(string[] args)
        {
            string ReturnValue = GetValueFromMethod();
            Console.WriteLine(ReturnValue.ToString());
            Console.ReadLine();
        }
        private static string GetValueFromMethod()
        {
            string ReturnValue = "Initial Value";
            try
            {
                int DividedByValue = 0;
                if (100 / DividedByValue == 0)
                {

                }
                return ReturnValue;
            }
            catch (Exception Ex)
            {
                // throw Ex;
                return "Catch Value";
            }
            finally
            {
                // The memory will be get cleared here
                ReturnValue = "Finally Value";
            }
        }   


Output: 

Catch Value



The main purpose of the finally is to free up the memory, but in the below case we can still assign the values in the finally block.


protected static string PassingValue = "Initial Value";
        static void Main(string[] args)
        {
            string ReturnValue = GetValueFromMethod();
            Console.WriteLine("Returned Value: "+ReturnValue.ToString());
            Console.WriteLine("PassingValue: " + PassingValue);
            Console.ReadLine();
        }
        private static string GetValueFromMethod()
        {           
            try
            {
                int DividedByValue = 0;
                if (100 / DividedByValue == 0)
                {

                }
                return PassingValue;
            }
            catch (Exception Ex)
            {
                // throw Ex;
                return "Catch Value";
            }
            finally
            {
                // The memory will be get cleared here, but assigning the values here again
                PassingValue = "Finally Value";
            }
        }
}


Output:

Returned Value: Catch Value
PassingValue: Finally Value

(To be continued)



  

Comments

Popular posts from this blog

Using of global variables in C# - Drawbacks & Solutions

How using global variables can have implications on the design, maintainability, and test-ability of C# code: Harder to understand and reason about the code:       class Program     {         public static int globalCounter = 0;         static void Main()         {             globalCounter++;             Console.WriteLine(globalCounter);         }     }   In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method. It's not clear where the value of the globalCounter is updated, it could be updated in other methods or classes, making it harder to trace the flow of data and understand the source of bugs.   More prone to errors:       class Program     {         public static string globalString;         static void Main()         {             globalString = "Hello" ;             Method1();             Method2();         }         static void Method1()         {

Task Parallel Library (TPL) and Akka.NET Alternatives

Task Parallel Library (TPL) and Akka.NET are among the most commonly used libraries for parallel and concurrent programming in the .NET ecosystem. However, there are also several other options available, depending on your specific needs: Parallel Language Integrated Query (PLINQ) is a parallel programming feature of .NET that provides an easy and efficient way to perform operations on collections in parallel. LINQ (Language Integrated Query) is a powerful feature in .NET that allows developers to work with data in a more declarative and language-integrated manner. While LINQ queries are inherently sequential, PLINQ extends LINQ by providing parallel versions of the query operators, allowing some queries to execute faster by utilizing multiple processors or cores on a machine. PLINQ is great when you are working with large collections where operations might be CPU-intensive or I/O-bound and could potentially be sped up by parallel execution. Here is a simple example of a PLI

SOLID Principles with Real World examples in C#

  SOLID Principles with Real World examples in C#   SOLID principles are formed by using S Single Responsibility Principles (SRP) O Open Closed Principle (OCP) L Liskov’s Substitution Principle (LCP) I Interface Segregation Principle (ISP) D Dependency Inversion Principle (DIP)   S Single Responsibility Principles (SRP) There should never be more than one reason for a class to change, to be precise one class should have only one responsibility Single Responsibility Principles (SRP) Real world example, A perfect match for SRP is Microservices , a Microservice will not contain functionalities other than the one it is designated to do,  Example ·                   Order Processing Service, ·                   Shipment Management Service, ·                   User Authentication Service, ·                   Catalogue List Service       class OrderProcessor     {         public void Process(Order order)         {             // Check inven