Exception Handling Framework in Selenium Scripts
Exceptions are events due to java program ends without giving expected output. Java provides a framework where the user can handle exceptions.
There are three kinds of exceptions:
- Checked Exception
- Unchecked Exception
The class hierarchy of exception and error:
Checked exception handle during compile time. It gives the compilation error if it is not caught and handled during compile time.
FileNotFoundException, IOException etc.
In the case of an unchecked exception, the compiler does not mandate to handle. The compiler ignores during compile time.
When a scenario is fatal and the program cannot recover then JVM throws an error. Errors cannot handle by try catch block. Even if the user tries to handle the error by using Try catch block, it cannot recover from error.
Assertion error, OutOfMemoryError etc.
Try and Catch block:
try-catch blocks are generally used to handle exceptions. Type of exceptions declares in catch block expect to come. When an exception comes in try block, immediately control moves to catch block. There can be many catch blocks for one try block depending upon the type of exception.
throws keyword in java use to throw an exception rather than handling it.
finally, block executes irrespective of execution of try catch block. It executes immediately after try/catch block completes. File close, database connection etc. can close in finally block. The BufferReader stream is closed in finally block. br.close() will always execute irrespective of execution of try and catch block.
finally block can exist without any catch block. It is not necessary to have a catch block always. There can be many catch blocks but only one finally block use.
Throwable is parent class for error and exception handle. Generally, it is difficult to handle errors in java. If the programmer is not sure about the type of error and exception. Then it is told to use the Throwable class which can catch both error and exception.
Selenium has its own set of exceptions. While developing selenium scripts, the programmer has to handle throw exceptions.
If selenium tries to find an element but element is not visible within page
If the user tries to handle an alert box but the alert is not present.
It trying to get attribute value. But the attribute is not available in DOM.
This exception is due to accessing an element which is not available in the page.
The exception comes when the code is unable to initialize WebDriver.
Online Selenium Training in Hyderabad: We provide professional Online Selenium Training in Hyderabad. We Provide Selenium live project.