Common Exceptions in Selenium & How to Handle Them.pdf

worthamsteveh 20 views 16 slides Oct 08, 2024
Slide 1
Slide 1 of 16
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16

About This Presentation

While executing an automated test scripts, testers and developers often come across scenarios where test script fails abruptly due to exceptions like element not being found,


Slide Content

CommonExceptionsinSelenium&
HowtoHandleThem
Testexecutionscanevenbehinderedbyintermittentnetwork
connectivityissues.Thesearejustafewexamplesofhowexceptions
candisruptanytestingprocess.Byunderstandinghowtohandle
theseexceptionseffectively,youcanpreventsuchroadblocksand
ensurethesmoothexecutionofyourtestscripts.
Seleniumisapowerfultoolfortestautomationandisresponsiblefor
ensuringthequalityandreliabilityofwebapplications.However,like
anysoftware,itisalsopronetoexceptionsthatcandisrupttest
execution.Theseexceptionscanariseduetovariousreasons,such
aselementunavailability,networkissues,orunexpectedpage
behavior.

TobuildrobustandmaintainableSeleniumtestscripts,it’scrucialto
gracefullyhandletheseexceptions.Byimplementingeffective
exceptionhandlingmechanisms,youcanpreventtestfailures,
improvetestreliability,andgainvaluableinsightsintopotentialissues
inyourapplication.
ThisblogwilldelveintocommonSeleniumexceptions,exploringtheir
causes,andprovidingpracticalsolutionstomitigatetheirimpact.By
masteringexceptionhandling,youcanelevateyourSeleniumtesting
capabilitiesandcreatemoreresilientautomationsuites.
WhatisExceptioninSelenium?
Anuncommonorunprecedentedeventthattakesplacewhilea
softwareprogramorapplicationisbeingexecutedisreferredtoasan
exception.Itisaruntimeerrorcausedbyanunforeseenoutcomeor
occurrencethataffectsandruinsregularprogramflow.Anexception
isseenasaflawaswell.
Whenanautomationtesterordeveloperwritesorexecutesa
Seleniumscript,thetestcanbeimpactedbyunforeseenissuesinthe
code,knownasexceptioninSelenium.
Whenanexceptionisencountered,anexceptionobjectiscreated
containingdebugginginformationlikethelinenumber,thetypeof
exception,andthemethodhierarchy.Oncethisexceptionobjectis
generatedandpassedtotheruntimeenvironment,theprocessis
called“throwingtheexception.”
TypesofExceptioninSelenium
InSelenium,exceptionsaremainlycategorizedintotwotypes:
1.CheckedExceptions

Checkedexceptionsareanticipatederrorsthatthecompilerforces
youtoacknowledgeandhandle.Theseexceptionstypicallyarisefrom
externalfactorsorresourceconstraints.Aclassicexampleis
attemptingtolocateanelementthatisnotpresentonthepage.The
compilermandatesthatyoueitherhandlethisexceptionusinga
try-catchblockordeclareitinthemethodsignature.Thisapproach
promotesrobustcodebycompellingdeveloperstoconsiderpotential
issuesbeforehand.
2.UncheckedExceptions
Unlikecheckedexceptions,uncheckedexceptionsarenotanticipated
bythecompilerandcanoccuratruntime.Theseexceptionsoften
stemfromprogrammingerrorsorunexpectedapplicationbehavior.
Examplesincludeattemptingtoaccessanelementthathasbecome
staleduetopagechangesorencounteringaNullPointerException
whenworkingwithobjectreferences.Whileit’sadvisabletohandle
theseexceptionstoenhancecodereliability,thecompilerdoesn’t
enforcetheirhandling,allowingformoreflexibilityincodestructure.
Listof33CommonSeleniumExceptions
Seleniumprovidesalistofpredefinedexceptionstohelpanalyzeand
debugtestsmoreefficiently.HerearesomecommonSelenium
exceptionlistsexplainedindetail:
●WebDriverException:Thisoccurswhenanactionisattempted
whiletheWebDriverconnectionisclosed.Itindicatesthatthe
WebDrivercannotinteractwiththebrowserbecausethesession
hasended.

●TimeOutException:Thisexceptionisthrownwhenacommand
exceedsthespecifiedordefaultwaittime.Ittypicallyoccurs
whenwaitingforanelementoroperationtocompletebutittakes
toolong.
●ElementNotVisibleException:ThisoccurswhenSeleniumtries
tolocateanelement(usinglocatorsinSelenium),butthe
elementisnotvisibleonthepage.Itmeanstheelementexistsin
theDOMbutishiddenfromview.
●NoSuchWindowException:ThishappenswhenSeleniumtries
toswitchtoawindowthatdoesnotexist.Itindicatesthatthe
targetwindowcannotbefound.
●NoSuchElementException:Thisexceptionisthrownwhen
Seleniumcannotfindanelementonthewebpage.Itoccurs
whentheelementdoesnotexistatall,unlikethe
ElementNotVisibleException,whichoccurswhentheelement
existsbutishidden.
●ElementNotInteractableException:Thisoccurswhenan
elementispresentintheDOMbutcannotbeinteractedwith.
Thismightbeduetooverlappingelementsorattemptingto
interactwiththeelementbeforeitisready.
●ConnectionClosedException:Thisexceptionoccurswhenthe
connectiontotheSeleniumdriverisunexpectedlyclosed,
preventingfurtherinteractionwiththebrowser.
●ElementClickInterceptedException:Thishappenswhenan
elementinterceptstheclickintendedforanotherelement,
preventingtheactionfrombeingcompleted.

●ElementNotSelectableException:Thisisthrownwhenan
elementexistsintheDOMbutcannotbeselected.The
WebDriverisunabletointeractwiththeelementduetoitsstate.
●ErrorHandler.UnknownServerException:Thisexceptionis
usedasaplaceholderwhenaserverreturnsanerrorwithout
providingastacktrace.Itsignifiesthatanunknownserver-side
erroroccurred,andthereisinsufficientinformationtodiagnose
theissue.
●ErrorInResponseException:Thisexceptiontypicallyoriginates
fromserver-sideerrors.Itindicatesthattheserverresponded
withanerror,whichtheSeleniumclientwasunabletohandle
properly.
●ImeActivationFailedException:ThisoccurswhentheInput
MethodEngine(IME),usedforinputtingmulti-bytecharacters
likeChineseorJapanese,failstoactivate.Itindicatesthatthe
systemcouldnotswitchtothedesiredinputmethod.
●ImeNotAvailableException:Similartothe
ImeActivationFailedException,thisoccurswhenIMEsupportis
unavailable.ItmeansthattherequiredInputMethodEngine
(IME)isnotavailableonthesystem,preventingtheinputof
multi-bytecharacters.
●InsecureCertificateException:Thishappenswhennavigating
toawebpagewithanexpiredorinvalidTLScertificate.It
indicatesthatthebrowserdetectedasecurityissuewiththe
site’scertificate,suchasitbeingexpiredornotbeingtrusted.

●InvalidArgumentException:Thisisthrownwhenaspecified
argumenttypedoesnotmatchanyexpectedtype.Itoccurs
whentheinputprovidedtoamethodorfunctionisnotofthe
correcttypeorformat.
●InvalidCookieDomainException:Thisexceptionoccurswhen
tryingtoaddacookieforaninvalidURLordomain.Itindicates
thatthedomainspecifiedforthecookieisnotvalid,possiblydue
toatypoorincorrectdomainstructure.
●InvalidCoordinatesException:Thisself-explanatoryexception
occurswheninvalidcoordinatesarespecifiedforanoperation.It
typicallyhappenswhentryingtoperformactionsthatrequire
specificscreencoordinates,suchasclickingordragging.
●InvalidSessionIdException:ThisisthrownwhenthesessionID
isinvalidbecausethesessionisinactiveorhasbeenterminated.
ItmeansthattheWebDriversessionbeingreferencednolonger
exists.
●InvalidElementStateException:Thisexceptionoccurswhen
Seleniumcannotcompleteacommandonaspecifiedelement
duetoitscurrentstate.Forexample,tryingtoclickadisabled
buttonorinteractwitharead-onlyfield.
●JavascriptException:Thisexceptionisthrownwhenthe
providedJavaScriptcodecannotbeexecutedorisincorrect.It
indicatesthattherewasanerrorinthescriptprovidedtothe
WebDriverforexecution.
●InvalidSwitchToTargetException:Thisoccurswhenswitching
todifferenttabs,windows,orframeswithincorrectarguments.It

indicatesthatthespecifiedtargetfortheswitchoperationdoes
notexistorisnotaccessible.
●JsonException:ThishappenswhentheSeleniumclientcannot
parsethereturnedvaluesfromanactionoroperation.It
indicatesthattheresponsefromtheserverorbrowsercouldnot
beproperlyconvertedintoausableformatduetoincorrector
malformedJSON.
●MoveTargetOutOfBoundsException:Thisoccurswhenthe
WebDrivertriestoaccessanelementoutsidetheviewport.This
canbemitigatedbyscrollingtheelementintoview.
●NoAlertPresentException:Thisexceptionisthrownwhenthe
codewrittentohandleanalertcannotfindthealertduring
execution.Ittypicallyoccurswhenyouattempttoswitchtoor
interactwithanalertthatisnotcurrentlypresentontheweb
page.
●NoSuchAttributeException:Thisexceptionoccurswhen
Seleniumtriestoaccessanattributeofanelementthatdoesnot
exist.Forexample,ifyoutrytogetthevalueofanon-existent
attribute,thisexceptionwillbethrown.
●NoSuchContextException:Typicallyencounteredduring
mobiledevicetesting,thisexceptionisthrownwhenthecontext
youaretryingtoswitchtocannotbefound.Contextsinmobile
testingcanrefertodifferentviewssuchasnativeappviewsand
webviews.
●NoSuchCookieException:Thisexceptionisthrownwhen
Seleniumcannotfindaspecifiedcookie.Itoccurswhenyou

attempttoretrieveordeleteacookiethatdoesnotexistinthe
browser’scookiestore.
●NoSuchFrameException:ThisoccurswhenSeleniumcannot
findthetargetiframe.Ittypicallyhappenswhenyoutrytoswitch
toaframethatdoesnotexistintheDOM.Thiscanoccurifthe
frameIDornameisincorrectoriftheframehasnotbeenloaded
yet.
●RemoteDriverServerException:Thisexceptionoccurswhen
theSeleniumserverdoesnotrespondduetoimproperly
describedcapabilities.Itindicatesaproblemwiththe
configurationorsetupoftheWebDriver,leadingtoafailurein
communicationwiththeserver.
●UnsupportedCommandException: Thisoccurswhenthe
remoteWebDriversendscommandsthatareinvalidornot
supported.Itindicatesthatthecommandbeingattemptedisnot
recognizedbytheWebDriverorthebrowserbeingused.
●StaleElementReferenceException:Thisexceptionisthrown
whenyoutrytointeractwithaDOMelementthatisnolonger
attachedtotheDOMtree.Thiscanhappeniftheelementhas
beenremovedorthepagehasbeenrefreshedorupdated,
makingthereferencetotheelementoutdated.
●SessionNotFoundException:Thisoccurswhenanactionis
performedwithoutanactiveWebDriversessionorifthesession
hasbeenterminated.ItindicatesthattheWebDriversessionyou
aretryingtousenolongerexists,possiblyduetoabrowser
crashormanualsessiontermination.

●SessionNotCreatedException:Thisexceptionisthrownwhen
theWebDrivercannotcreateanewsession.Itcanhappendue
tovariousreasonssuchasincorrectWebDriverconfiguration,
incompatiblebrowserversion,orissueswiththeWebDriver
binaryitself.
WhatisExceptionHandlinginSelenium?
ExceptionhandlinginSeleniuminvolvestheprocessofdetectingand
managingerrorsthatoccurduringtheexecutionoftestscripts.When
anunforeseeneventorerrordisruptsthenormalflowofaSelenium
script,exceptionhandlingmechanismsallowdeveloperstomanage
thesedisruptionsgracefully.Thisensuresthatthetestexecutiondoes
notabruptlystop,andappropriateactionscanbetakentoaddressor
logtheissues.Properexceptionhandlinghelpsincreatingresilient
andreliableautomationtestsbyenablingthescriptstohandle
unexpectedsituationseffectivelyandcontinuerunningorprovide
meaningfulfeedback.
Ifanexceptionisnothandledappropriately,therestofyourtestsmay
alsofail.Theinabilitytodifferentiatebetweenanapplicationproblem
andaSeleniumproblemduetotheExceptioninSelenium
complicatestheinterpretationofautomationresults.
DifferentMethodstoHandleExceptionIn
Selenium
ExceptionhandlinginSeleniumWebDriverinvolvesvarious
techniquestomanageerrorsandensuresmoothexecutionoftest
scripts.Herearesomestandardmethodsforhandlingexceptionsin
SeleniumWebDriver:
1.Try-Catch

Thetry-catchconstructisthefoundationalmethodforhandling
exceptions.Thetryblockcontainsthecodethatmightthrowan
exception,whilethecatchblockhandlestheexceptionifoneoccurs.
Thismethodallowsyoutoprotectsectionsofcodethatmightfailand
handleerrorsgracefully.
Syntax:
Copy
Copy
try{
//Codethatmightthrowanexception
}catch(Exceptione){
//Codetohandletheexception
}
2.MultipleCatchBlocks
Whendealingwithvarioustypesofexceptionsthatmightarisefroma
singleblockofcode,youcanusemultiplecatchblocks.Eachcatch
blockcanhandleaspecifictypeofexception,allowingformore
preciseerrormanagement.Youcanhaveasmanycatchblocksas
needed.
Syntax:
Copy
Copy
try{
//Codethatmightthrowexceptions
}catch(ExceptionType1e1){
//HandleExceptionType1
}catch(ExceptionType2e2){
//HandleExceptionType2
}

3.Throw/Throws
●Throw:Thethrowkeywordisusedtoexplicitlythrowan
exceptionfromwithinamethod.Thisisusefulwhenyouwantto
passanexceptiontothecallingmethodforhandling.
Syntax:
Copy
Copy
publicstaticvoidanyFunction()throwsException{
try{
//Codethatmightthrowanexception
}catch(Exceptione){
//Handletheexception
throwe;//Re-throwtheexception
}
}
●Throws:Thethrowskeywordisusedinamethodsignatureto
indicatethatthemethodmightthrowspecificexceptions.It
informsthecallerofthemethodaboutpotentialexceptionsthat
needtobehandled.
Syntax:
Copy
Copy
publicstaticvoidanyFunction()throwsExceptionType1,
ExceptionType2{
//Methodcode

}
4.Finally
Thefinallyblockisusedtoexecutecodethatshouldrunregardlessof
whetheranexceptionwasthrownornot.Thisisusefulforcleanup
operations,suchasclosingfilesorreleasingresources.
Syntax:
Copy
Copy
try{
//Codethatmightthrowanexception
}catch(ExceptionType1e1){
//HandleExceptionType1
}catch(ExceptionType2e2){
//HandleExceptionType2
}finally{
//Codethatalwaysexecutes
}
5.ExceptionInformationMethods
Togetdetailedinformationaboutexceptions,youcanusethe
followingmethods:
●printStackTrace():Printsthestacktraceoftheexception,
includingtheexceptionnameandadescription,whichhelpsin
debugging.
●toString():Returnsastringrepresentationoftheexception,
includingitsnameanddescription.

●getMessage():Retrievesthedescriptionoftheexception,
providingmorecontextaboutwhatwentwrong.
Byusingthesetechniques,youcaneffectivelymanageexceptionsin
SeleniumWebDriver,ensuringthatyourtestscriptshandleerrors
gracefullyandprovidemeaningfulfeedback.
ExceptionHandlingBestPractices
Effectiveexceptionhandlingiskeytodevelopingrobustandreliable
automationtests.Herearesomebestpracticestofollow:
●HandleCommonConditionsWithoutThrowingExceptions:
Anticipateandaddresscommonconditionsorerrorsinyour
codewithoutrelyingonexceptions.Thishelpsprevent
unnecessaryexceptionhandlingandkeepsyourcodecleaner.
●DesignClassesorMethodstoAvoidExceptions:Structure
yourclassesandmethodstominimizethelikelihoodof
exceptions.Properdesignandvalidationcheckscanprevent
errorsfromoccurringinthefirstplace.
●PredictExceptionsandUseTry/Catch/FinallyBlocks:
Anticipatepotentialexceptionsandincludetry-catch-finally
blocksinyourcodetohandlethemgracefully.Thisensuresthat
yourprogramcanmanageerrorseffectivelyandcontinue
running.
●WriteMeaningfulErrorMessages:Provideclearand
informativeerrormessagesinyourcatchblocks.Thishelpsin
diagnosingtheproblemquicklyandunderstandingthecontextof
theerror.

●CreateCustomExceptionsWhenNeeded:Definecustom
exceptionstomakeerrorhandlingmorereadableandspecificto
yourapplication’sneeds.Customexceptionscanprovidemore
meaningfulerrormessagesandenhancecodeclarity.
●CatchSpecificExceptionTypes:Avoidusinggeneric
Exceptionincatchblocks.Instead,catchspecificexceptionslike
ArithmeticExceptiontohandledifferenterrorscenariosmore
precisely.
●UseProperNamingConventionsforCustomExceptions:
Followconsistentnamingconventionswhencreatingcustom
exceptions.Thisimprovescodereadabilityandhelpsin
identifyingthepurposeoftheexceptioneasily.
●DifferentiateBetweenTestCaseErrorsandCodingErrors:
Distinguishbetweenerrorsthatoccurduetotestcasefailures
(e.g.,assertionerrors)andthosecausedbycodingissues.This
helpsinisolatingandaddressingproblemsmoreeffectively.
●UsetheFinallyBlockforResourceCleanup:Ensurethat
resourcessuchasfilehandlesordatabaseconnectionsare
properlyclosedusingthefinallyblock.Thisguaranteesthat
resourcesarereleasedregardlessofwhetheranexceptionwas
thrown.
Conclusion
ExceptionsinSeleniumandhandlingthemisacriticalcomponentof
everySeleniumscript,asitensuresthatthetestsrunsmoothlyeven
whenunexpectederrorsoccur.Ignoringexceptionscanleadto
disruptionsinthenormalexecutionofprograms,makingrobust

exceptionhandlingessentialformaintainingthereliabilityof
automatedtests.
Source:Thisarticlewasoriginallypublishedattestgrid.io.