Exception Handling

In this lecture, we will talk about one of the most important topics every automation tester should know ...Exception Handling

So whats an Exception?
Well, they are problems in your code that occur during the execution of a program.

Why Do I Handle Them?
If not handled, the program execution terminates

Ok, Tell Me How To Handle Them?
Exceptions can be handled using 3 keywords(try, catch and finally)

We will take our previous lecture example of querying dictionary with a key whose entry is not added in the dictionary.

Check the below code

//Initialization
Dictionary<string, string> stateCollection = new Dictionary<string, string>(); //Adding Data
stateCollection.Add("CA", "California");
stateCollection.Add("CO", "Colorado");
stateCollection.Add("NY", "New York");
stateCollection.Add("TX", "Texas"); 
//Querying Dictionary
var value=stateCollection["CA1"];
Here we while querying the dictionary to return value for key "CA1", we will get an exception as we have not added the key earlier, below is the exception we will get

System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.'

We can use ContainsKey or TryGetValue methods to avoid this exception however here we will handle the exception using try, catch block
try    
{               
//Querying Dictionary
var value = stateCollection["CA1"];
}
catch (KeyNotFoundException ex)
{
//Code to handle exception goes here
Console.WriteLine($"Exception while querying the dictionary-{ex.Message}");
} 
Console.WriteLine("Code after try block");
Console.Read();
Here, once the exception arises in the try block then the control jumps to the catch block and executes the exception handling code, in our case printing on console
After that, it prints "Code after try block"on console.

Below output-

Exception while querying the dictionary-The given key was not present in the dictionary.
Code after try block

Here you would have noticed our program did not terminate as we handled the exception.
We can add multiple catch blocks around a single try block, which will catch specific exceptions
Check below code
try
{
//Querying Dictionary
var value = stateCollection["CA1"];
}
catch (KeyNotFoundException ex)
{
//Code to handle exception goes here
Console.WriteLine($"Key not found exception while " +
                $"querying the dictionary-{ex.Message}");
}
catch (NullReferenceException ex)
{
//Code to handle exception goes here
Console.WriteLine($"Null exception while " +
               $"querying the dictionary-{ex.Message}");
}
catch (Exception ex)
{
//Code to handle exception goes here
Console.WriteLine($"Exception while querying" +
               $" the dictionary-{ex.Message}");
throw new Exception("Error Occured");
}
finally
{
Console.WriteLine("Code in finally block");
}
Console.WriteLine("Code after try block");
Console.Read();
        }
    }
}


Here you can see, we have 3 catch blocks for handling 3 different types of exceptions.
If there is an exception in try block code then it will first check if that exception is of type KeyNotFoundException if yes then it will execute code in the catch block else it will move to next catch block and so on.

Note- We have last catch block which is of type Exception, here if there is an exception which is not handled by any of the above blocks then code in this block is executed.

In the last catch block, we have below line
throw new Exception("Error Occured");

throw keyword is used to create and throw Exceptions to calling code.

 Now we will talk about finally block, the code in finally block is executed even if an exception is thrown or not thrown.
finally, block mostly contains code to release resources like closing database connections, closing file streams etc

Output:-

Key not found exception while querying the dictionary-The given key was not present in the dictionary.
Code in finally block
Code after try block


Points to remember
  1. Exceptions are types that derive from System.Exception
  2. Always use try block around the code which might throw exceptions
  3. Exception variable in out catch block provides more information related to the exception, in our above example we are just getting the message using ex.message
  4. One can explicitly throw a new exception using throw keyword
  5. The code in finally block is executed even if an exception is thrown or not thrown.

That's all for this lecture 




Comments

Popular posts from this blog

Specflow -Part3(Working with tables using Specflow.Assist.Dynamic)

Specflow -Part4(Specflow Scenario Outline and Feature Background )

Specflow -Part6(Specflow Hooks)