Exception Handling In Scripting as well as in Life.

Kishor Munot
6 min readAug 5, 2023

--

Exception Handling

Hello Everyone,

In this blog, we will discuss exceptions. Any exception comes suddenly in your life and if you don’t handle that exception properly, it can cause you a lot of trouble. We should handle any kind of exception properly because if we handle exceptions properly, our goal will be accomplished quickly.

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.

Difference between Error and Exception

An Error “indicates serious problems that a reasonable application should not try to catch.”

An Exception “indicates conditions that a reasonable application might want to catch.”

Whenever an error occurs while executing a statement, it creates an exception object and then the normal flow of the program halts and it tries to find someone that can handle the raised exception. The exception object contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception, etc. When the exception occurs in a method, the process of creating the exception object and handing it over to the runtime environment is called *“throwing the exception”.

Suppose you are watching a video on Youtube, and suddenly, your internet connectivity is disconnected or not working. In this case, you are not able to continue watching the video on Youtube. This interruption is nothing but an exception. If YouTube didn’t handle this kind of exception with a clear message and fix the problem, the user wouldn’t understand why my video stopped suddenly and the user wouldn’t be able to use YouTube again.

Suppose a person is traveling by car from Mumbai to Pune. After traveling mid-distance, the tire of his car is punctured. This unexpected or unwanted event is nothing but an exception.

The car owner always keeps an extra tire as an alternative on a long-distance journey to handle these types of exceptions. He changes the punctured tire with a new tire. After changing the tire, he continues the rest of the journey. This alternative way is called exception handling.

Hope so you got what I am saying about exception handling so let's start with how to handle exceptions in Selenium with Java.

Exception Handling with Selenium Java

The Exceptions are classified mainly into two types:

  • Checked Exceptions: These exceptions are handled while writing the code itself before the compilation of the code, and hence they are examined at the compile time.
  • Unchecked Exceptions: These exceptions get thrown at run time and are more catastrophic as compared to Checked Exceptions.

We face some common exceptions while executing the tests in the selenium.

  1. ElementNotSelectableException: An element is disabled (can not be clicked/selected) in spite of being present in the DOM
  2. ElementNotInteractableException: An element is not in a state, where it can be interacted with (can not be clicked or able to send keys) in spite of it being present in the DOM
  3. ElementNotVisibleException: In spite of the element being present in the DOM, it is not visible (can not be interactive). For example, elements defined in HTML with type =”hidden”. It is a subclass of the ElementNotInteractableException
  4. NoSuchElementException: Webdriver is not able to determine the elements during runtime, i.e., the FindBy method cannot find a particular component
  5. NoSuchFrameException: Webdriver attempts to switch to an invalid frame, which is unavailable
  6. NoAlertPresentException: Webdriver is trying to switch to an invalid alert, which is unavailable
  7. NoSuchWindowException: Webdriver is trying to switch to an invalid window, which is unavailable
  8. StaleElementReferenceException: The referenced element is no longer present on the DOM page (a reference to a component is now Stale). For example, the item belongs to a different frame than the current one or the user has navigated away to another page
  9. SessionNotFoundException: Webdriver is acting immediately after ‘quitting’ the browser
  10. TimeoutException: The command did not complete in the specified time. For example, the element didn’t display at the specified time. This is especially encountered when working with waits
  11. WebDriverException: Webdriver is acting immediately after ‘closing’ the browser.

Selenium WebDriver employs the avoid-handle strategy as a method for handling potential exceptions that can arise while running tests. The method consists of two key strategies: dealing with Selenium exceptions when they do arise and preventing them whenever possible.

Try-catch

This method can catch Exceptions by using a combination of the try-and-catch keywords. Try indicates the start of the block, and Catch is placed at the end of the try block to handle or resolve the Exception. The code that is written within the Try/Catch block is referred to as “protected code.” The following code represents the syntax of Try/Catch

try
{
// Some code
}
catch(Exception e)
{
// Code for Handling the exception
}

Multiple-catch-blocks

There are various types of Exceptions, and one can expect more than one exception from a single block of code. Multiple catch blocks are used to handle every kind of Exception separately with a separate block of code. One can use more than two catch blocks, and there is no limitation on the number of catch blocks.

try
{
//Some code
}
catch(ExceptionType1 e1)
{
//Code for Handling the Exception 1
}
catch(ExceptionType2 e2)
{
//Code for Handling the Exception 2
}

Finally

The Finally keyword is used to create a block of code under the try block. This finally code block always executes irrespective of the occurrence of an exception

try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
finally
{
//The finally block always executes.
}

Why exception Handling is important in Selenium.

  1. Think of a situation where you have got an exception and you want to print some custom message in your logs so that it can be understandable by the whole team.
  2. There can be some situations where you want to just eat up the exception and want your test to carry on with the rest of the execution.
  3. In case you want to perform some series of steps on occurring of a certain exception for e.g. if you got an exception because a product is out of stock, that product is no longer displayed on the page and you want to go with another product available on the page.
  4. In case you want to handle some certain kind of exception in Selenium like ElementNotSelectableException, ElementNotVisibleException, NoSuchElementException, etc. exceptions.

See the code below where I handle the exceptions that occur most often so I can understand why my tests are failing and I can fix issues.

public static WebElement btn_ReportCategory(WebDriver driver) throws Exception{

try{

WebElement element = driver.findElement(By.linkText("+ Report Categories"));

}catch (Exception e){

// Printing logs for my report

Log.error("Report Category button element is not found.");

// Taking screenshot for defect reporting

Utils.captureScreenShot();

// After doing my work, now i want to stop my test case

throw(e);

}

// This will return the Element in case of no Exception

return element;

}

Exception Handling Best Practices

I would like to share best practices to handle exceptions so please implement those in your scripting and handle your issues and fix them.

  • Handle common conditions without throwing exceptions
  • Design classes or methods so that exceptions can be avoided
  • Always predict the exception and have a try/catch/finally block inside your code
  • Write meaningful error messages
  • Create a custom exception as and when required to make it more readable
  • Catch the exception with the exact exception type; for example, rather than using Exception use the concrete exception type ArithmethicException
  • Use the proper naming conventions when defining the custom exceptions
  • Differentiate between the test case errors (Assertion errors) and coding errors
  • Use the final block to clean up the resources

Thank you for reading my blog. Please share your thoughts on my writing.

Keep Reading, Keep Enjoying, and Keep testing.

Thank you.

--

--