Which type of catch block is used to catch all types of exceptions in C ++? Answer choices select only one option catch ()?

In Java 7, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication. Let’s understand java catch multiple exceptions feature with an example.

Java catch multiple exceptions

Which type of catch block is used to catch all types of exceptions in C ++? Answer choices select only one option catch ()?
Before Java 7, we used to catch multiple exceptions one by one as shown below.

catch (IOException ex) { logger.error(ex); throw new MyException(ex.getMessage()); catch (SQLException ex) { logger.error(ex); throw new MyException(ex.getMessage()); }

In Java 7, we can catch both these exceptions in a single catch block as:

catch(IOException | SQLException ex){ logger.error(ex); throw new MyException(ex.getMessage()); }

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can’t change it. The byte code generated by this feature is smaller and reduce code redundancy.

Java rethrow exception

Another improvement is done in Compiler analysis of rethrown exceptions. Java rethrow exception allows you to specify more specific exception types in the throws clause of a method declaration. Let’s see this with a small example:

package com.journaldev.util; public class Java7MultipleExceptions { public static void main(String[] args) { try{ rethrow("abc"); }catch(FirstException | SecondException | ThirdException e){ //below assignment will throw compile time exception since e is final //e = new Exception(); System.out.println(e.getMessage()); } } static void rethrow(String s) throws FirstException, SecondException, ThirdException { try { if (s.equals("First")) throw new FirstException("First"); else if (s.equals("Second")) throw new SecondException("Second"); else throw new ThirdException("Third"); } catch (Exception e) { //below assignment disables the improved rethrow exception type checking feature of Java 7 // e=new ThirdException(); throw e; } } static class FirstException extends Exception { public FirstException(String msg) { super(msg); } } static class SecondException extends Exception { public SecondException(String msg) { super(msg); } } static class ThirdException extends Exception { public ThirdException(String msg) { super(msg); } } }

As you can see that in rethrow method, catch block is catching Exception but it’s not part of throws clause. Java 7 compiler analyze the complete try block to check what types of exceptions are thrown and then rethrown from the catch block. Note that this analysis is disabled if you change the catch block argument. Further Reading: Exception Handling in Java.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up

“Exception” is a quite common term when it comes to programming, regardless of which language you use to write codes.

Exceptions in Selenium are like enemies for programmers—they are unavoidable. Even if you work with other automation testing tools such as Katalon Studio, you may still face these types of exceptions (because Katalon Studio is built on top of Selenium). They are, however, more easily fixable than bugs or errors as they can throw logical termination.

This article will provide you with a complete list of exceptions in Selenium as well as the cases in which they occur.

What are Selenium exceptions?

Definition

An exception is known as an unusual or unprecedented event that occurs during the execution of a software program or application. It is a runtime error of an unexpected result or event which influence and disrupt usual program flow. An exception is also considered as a fault.

Classification of Selenium exceptions

Selenium exceptions are divided into two types including Checked Exceptions and Unchecked Exceptions.

1. Checked Exceptions

Checked Exceptions are handled during the process of writing codes. These exceptions are handled before compiling the code, therefore, such exceptions are examined at the compile time.

2. Unchecked Exceptions

These exceptions are thrown at runtime. Unchecked exceptions are more catastrophic than the compile-time exception as it causes problems while running Automation pack in headless.

The complete list of exceptions in Selenium

1. ConnectionClosedException: This exception takes place when there is a disconnection in the driver.

2. ElementClickInterceptedException: The command could not be completed as the element receiving the events is concealing the element which was requested clicked.

3. ElementNotInteractableException: This Selenium exception is thrown when an element is presented in the DOM but it is impossible to interact with such element.

4. ElementNotSelectableException: This Selenium exception is thrown when an element is presented in the DOM but is unavailable for selection. Hence, it is impossible to interact with.

5. ElementNotVisibleException: This type of Selenium exception takes place when an existing element in DOM has a feature set as hidden. In this situation, elements are there, but you can not see and interact with the WebDriver.

6. ErrorHandler.UnknownServerException: Exception is used as a placeholder if the server returns an error without a stack trace.

7. ErrorInResponseException: This exception is thrown when a fault has occurred on the server-side. You can see it happens when interacting with the Firefox extension or the remote driver server.

8. ImeActivationFailedException: This exception occurs when IME engine activation has failed.

9. ImeNotAvailableException: This exception takes place when IME support is unavailable.

10. InsecureCertificateException: Navigation made the user agent to hit a certificate warning, which is caused by an invalid or expired TLS certificate.

11. InvalidArgumentException: This Selenium exception is thrown if an argument does not belong to the expected type.

12. InvalidCookieDomainException: This happens when you try to add a cookie under a different domain rather than the current URL.

13. InvalidCoordinatesException: This happens if the coordinates offered to an interacting operation are not valid.

14. InvalidElementStateException: This Selenium exception occurs if a command cannot be finished as the element is invalid.

15. InvalidSessionIdException: Takes place when the given session ID is not included in the list of active sessions, which means the session does not exist or is inactive either.

16. InvalidSwitchToTargetException: Happens if the frame or window target to be switched does not exist.

17. JavascriptException: This problem happens when executing JavaScript supplied by the user.

18. JsonException: Happens when you afford to get the session capabilities where the session is not created.

19. MoveTargetOutOfBoundsException: Takes place if the target provided to the ActionChains move() methodology is not valid. For example: out of the document.

20. NoAlertPresentException: Happens when you switch to no presented alert.

21. NoSuchAttributeException: Occurs when the attribute of the element could not be found.

22. NoSuchContextException: Happens in mobile device testing and is thrown by ContextAware.

23. NoSuchCookieException: This exception is thrown if there is no cookie matching with the given path name found amongst the associated cookies of the current browsing context’s active document.

24. NoSuchElementException: Happens if an element could not be found.

25. NoSuchFrameException: Takes place if frame target to be switch does not exist.

26. NoSuchWindowException: Occurs if window target to be switched does not exist.

27. NotFoundException: This exception is a subclass of WebDriverException. It happens when an element on the DOM does not exist.

28. RemoteDriverServerException: This Selenium exception is thrown when the server does not respond due to the problem that the capabilities described are not proper.

29. ScreenshotException: It is impossible to capture a screen.

30. ScriptTimeoutException: Thrown when executeAsyncScript takes more time than the given time limit to return the value.

31. SessionNotCreatedException: A new session could not be successfully created.

32. SessionNotFoundException: The WebDriver is performing the action right after you quit the browser.

33. StaleElementReferenceException: This Selenium exception happens if the web element is detached from the current DOM.

34. TimeoutException: Thrown when there is not enough time for a command to be completed.

35. UnableToCreateProfileException: You can open a browser with certain options using profiles, but sometimes a new version of the Selenium driver server or browser may not support the profiles.

36. UnableToSetCookieException: Occurs if a driver is unable to set a cookie.

37. UnexpectedAlertPresentException: This Selenium exception happens when there is the appearance of an unexpected alert.

38. UnexpectedTagNameException: Happens if a support class did not get a web element as expected.

39. UnhandledAlertException: It happens when there is an alert, but WebDriver is unable to perform Alert operation.

40. UnknownMethodException: Thrown when the requested command matches with a known URL but not matching with a methodology for that URL.

41. UnreachableBrowserException: This Selenium exception happens if the browser is unable to be opened or has crashed because of some reasons.

42. UnsupportedCommandException: Occurs when remote WebDriver does not send valid commands as expected.

43. WebDriverException: This takes place when the WebDriver is performing the action right after you close the browser.

Selenium exceptions handling

What is Exception handling?

In a software program, an atypical event (e.g. unrecognized messages) can interfere with the regular execution flow. These events, if not handled properly, can result in termination of the program by immediate throwing exceptions. Handling exceptions is the process of managing these atypical events in order to prevent such problems from arising.

Selenium exception solutions

In order to handle these above types of Selenium exceptions, this article will discuss some compiler directives to support exception handling.

  • Throw: Throw keyword is used to throw exception to the runtime to handle it.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// Method Signature\

public static void anyFunction ( ) throws Exception {

try {

// write your code here

} catch ( Exception e ) {

// Do whatever you wish to do here

// Now throw the exception back to the system

throw ( e ) ;

}

}

  • Multiple Catch blocks: You can have multiple @catch() blocks to catch different types of exception. The syntax for multiple catch blocks looks like the following:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

try

{

   //Some code

} catch ( ExceptionType1 e1 ) {

   //Code for Handling the Exception 1

} catch ( ExceptionType2 e2 ) {

   //Code for Handling the Exception 2

}

  • Try/Catch: A @try block encloses code that can potentially throw an exception. A @catch() block contains exception-handling logic for exceptions thrown in a @try block. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try

{

// Some code

} catch ( Exception e ) {

// Code for Handling the exception

}

  • Finally: A @finally block contains code that must be executed whether an exception is thrown or not:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

try

{

   //Protected code

} catch ( ExceptionType1 e1 )

{

   //Catch block

} catch ( ExceptionType2 e2 )

{

   //Catch block

} catch ( ExceptionType3 e3 )

{

   //Catch block

} finally

{

   //The finally block always executes.

}

Selenium exception examples

Example 1: TimeoutException using Selenium WebDriver.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import static com . kms . katalon . core . testobject . ObjectRepository . findTestObject

import org . openqa . selenium . TimeoutException

import com . kms . katalon . core . logging . KeywordLogger

import com . kms . katalon . core . util . KeywordUtil

import com . kms . katalon . core . webui . keyword . WebUiBuiltInKeywords as WebUI

try {

WebUI . click ( findTestObject ( "Page_Register/btn_register" ) )

} catch ( TimeoutException toe ) {

WebUI . waitForElementClickable ( findTestObject ( "Page_Register/btn_register" ) , 20 )

WebUI . click ( findTestObject ( "Page_Register/btn_register" ) )

} catch ( Exception e ) {

KeywordUtil . markError ( "Register button is not found." )

throw ( e ) ;

}

Example 2: Let’s assume that in Selenium WebDriver you want to verify the presence of any element on the page. You would not be able to get this with an element locator. If the element is present, your locator will work and you will easily be able to print that the element is present. However, in this case, your element is not present on the page, your locator fails and simply throws the exception. Therefore, this case would be easily solved by using the self-written function.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import static com . kms . katalon . core . testobject . ObjectRepository . findTestObject

import org . openqa . selenium . WebDriver

import com . kms . katalon . core . webui . common . WebUiCommonHelper

boolean verifyObjectPresent ( ) {

try {

WebUiCommonHelper . findWebElement ( findTestObject ( "Page_Report/lblReport" ) , 20 )

return true ;

} catch ( Exception e ) {

return false ;

}

}

Conclusion

We have listed all types of exceptions in Selenium along with their explanations above. From here, you can create robust and optimal codes in Selenium as well as Katalon Studio by handling these exceptions wisely. We hope this article will be a quick reference for you to tackle exceptions in Selenium and Katalon Studio.

Which type of catch block is used to catch all types of exceptions in C ++? Answer choices select only one option catch ()?

Which type of catch block is used to catch all types of exceptions in C?

2) There is a special catch block called the 'catch all' block, written as catch(…), that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so the catch(…) block will be executed.

Which class can catch all exceptions?

Throwable is the superclass of all exceptions and errors. You can use it in a catch clause, but you should never do it! If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors.

Which block is useful to catch an exception?

Java catch block is used to handle the Exception by declaring the type of exception within the parameter.

What are the 3 types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.