How are Exceptions Handled in Selenium ?



What is an Error? 
Error is a bug in application the we may not want to catch .

What is an Exception?
An Exception is an event, which occurs during the execution of a program, and disrupts the normal flow of the 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.

Exceptions in Selenium
1) NoSuchElementException : Is thrown when "FindBy" method is not able to find the element.
2) StaleElementReferenceException : This tells that the element is no longer appears on the DOM page.
3) TimeoutException: This tells that the execution is failed because the command did not complete in enough time.
4) ElementNotVisibleException: Is thrown to indicate that although an element is present on the DOM, but it is not visible, and so is not able to be interacted with . 
5) ElementNotSelectable Exception:  Is thrown to indicate that the element is not Selectable, the possible causes for this might be that it is disabled .

Exception Handling in Selenium
What we might want to do when an exception occurs? 
1) We might want to just eat up the exception and let the test to carry on with rest of the execution.
2) Or we might want to print some custom message in the logs, so that it can be understood by the whole team.
3) Or we might want to perform some series of steps .




How to Handle Exception
A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code,

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


Multiple Catch blocks: A try block can be followed by multiple catch blocks. Like I said earlier, that there are multiple exceptions and you can expect more than one type of exception on a single code block and if you like to handle each type of exception separately with a separate block of code.

try { 
             // Some code
 }catch(Exception1 e1){ 
           // Code for Handling the exception 1
}catch(Exception2 e2){ 
           // Code for Handling the exception 2
}

Note: If the exception does not match with any exception type mentioned in the catch blocks, then it falls through all catches, and exception is thrown, execution stops. That is why it is advisable to include default exception block (“finally”) as well in the end, so that in the worst scenario if no catch block is able to catch the exception , it can be handled by the default exception.
In some cases when we don't want the program to execute further if it encounters certain Exception, then we can use Throw .

Throws: When we are throwing any exception in a method , then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method.
"Throwskeyword gives a method flexibility, of throwing an Exception rather than handling it.


Throw: "Throw" keyword is used to actually throw the exception at the run time .
Difference between Throws and Throw 
1) You can declare multiple exception thrown by method in throws keyword by separating them in common e.g. throws IO Exception, ArrayIndexBoundException etc, while you can throw only one instance of exception using throw keyword e.g. throw new IO Exception("not able to open connection").
2). While "Throws" can be used only  in method signature , whereas there are numerous places where we can use "Throw" :
       a)  anywhere  inside method or static initializer block 
static{
        try {
            throw new Exception("Can Not initialize");
        } catch (Exception ex) {
            Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

       b) "
Throwcan also be used instead of "returnin a method.
public void shutdown() throws IOException{
        throw new IOException("Unable to shutdown");
 }

 private static boolean shutdown() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

Note that in the method shutdown() above, a boolean should be returned. But because we have "
throw" in place of return , compiler understands that this method will always throw exception .
         c) "Throw" keyword can also be used instead of "break" keyword, to break out of a switch statement .

int number = 4;
switch(number){
            case 1:
                throw new RuntimeException("Exception number 1");
            case 2:
                throw new RuntimeException("Exception number 2");
        }

Finally
The "finally" keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Also it is useful in a case where exception is not caught by any of the "catch" blocks
try 
            { 
               //Protected code

            }catch(ExceptionType1 e1) 
            { 
               //Catch block 
            }catch(ExceptionType2 e2) 
            { 
               //Catch block 
            }catch(ExceptionType3 e3) 
            { 
               //Catch block 

            }finally 
            { 
               //The finally block always executes.

            }

 < Previous                                                                              Next >