Starting Out with C++: Early Objects (9th Edition)
Starting Out with C++: Early Objects (9th Edition)
9th Edition
ISBN: 9780134400242
Author: Tony Gaddis, Judy Walters, Godfrey Muganda
Publisher: PEARSON
bartleby

Concept explainers

Expert Solution & Answer
Book Icon
Chapter 16.1, Problem 16.4CP

Explanation of Solution

The “try” block:

  • The “try” block is starts with the keyword “try” and it contains the code which will have the possibility to generate an exception.
  • The “try” block must be followed by one or more “catch” blocks which are denoted as exception handlers.

The “catch” block:

  • The “catch” block is starts with the keyword “catch” and it is followed by an “exception parameter”.
  • The Catch block contains the code to be executed when the error occurred in Try block.

The general syntax for “try/catch” as follows:

try

{

//code which causes an exception;try block

}

Catch(Exception_argument)

{

//code which handles the exception;catch block

}

//Repeat catch blocks as many as needed

Process of the “try/catch” blocks:

  • The “try” block contains a block of statements which may cause an exception to be thrown.
  • Once an exception is caught, it has to be thrown to the “catch” block using “throw” statement. After executing the “catch” block, the program resumes at the statement, which follows the “try/catch” blocks.

Example:

For example, consider the below code containing an exception handler for dividing two integers:

#include <iostream>

#include <string>

using namespace std;

//function definition of "divide"

double divide(int a, int b)

{

//The value of "b" is 0

if (b == 0)

{

//declare and define the string

string exception="ERROR: denominator should not be 0...

Blurred answer
Students have asked these similar questions
If an exception is raised and the program does not handle it with a try/exceptstatement, what happens?
If an exception is thrown outside a try block, what are the probable outcomes?
Is there any way to skip Finally block of exception even if some exception occurs in the exception block?

Chapter 16 Solutions

Starting Out with C++: Early Objects (9th Edition)

Knowledge Booster
Background pattern image
Computer Science
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
SEE MORE QUESTIONS
Recommended textbooks for you
Text book image
Microsoft Visual C#
Computer Science
ISBN:9781337102100
Author:Joyce, Farrell.
Publisher:Cengage Learning,
Text book image
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning