Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
C++ Fundamentals

You're reading from   C++ Fundamentals Hit the ground running with C++, the language that supports tech giants globally

Arrow left icon
Product type Paperback
Published in Mar 2019
Publisher
ISBN-13 9781789801491
Length 350 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Antonio Mallia Antonio Mallia
Author Profile Icon Antonio Mallia
Antonio Mallia
Francesco Zoffoli Francesco Zoffoli
Author Profile Icon Francesco Zoffoli
Francesco Zoffoli
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

C++ Fundamentals
Preface
1. Getting Started FREE CHAPTER 2. Functions 3. Classes 4. Generic Programming and Templates 5. Standard Library Containers and Algorithms 6. Object-Oriented Programming 7. Appendix

The try-catch block


During the execution of a program, an anomaly may occur. We refer to these runtime problems as exceptions, and they represent the response to an exceptional circumstance that arises outside of the normal functioning of a program. Designing code that's resilient to errors is one of the hardest things a programmer has to deal with.

Exceptions are generally thrown using the throw keyword when something that cannot be handled is encountered by the program. This is also referred to as raising an exception.

The try keyword is followed by a block containing statements that might throw one or more exceptions. These exceptions can be caught by one or more catch clauses, which are sequentially listed after the try block. The syntax for this is as follows:

try {
  statement1;
} catch (exception-declaration1) { 
  statement2; 
} catch (exception-declaration2) { 
  statement3; 
}
...

A catch block consists of the catch keyword, the exception declaration, and a block. Based on the exception thrown inside the try block, one catch clause is selected and the corresponding block is executed. Once the catch block has terminated, the program continues its execution with the statement following the last catch clause.

Let's examine the following example to understand how try-catch conditional statements handle exceptions:

#include <iostream> 
int main() 
{ 
  int x = 10; 
  try { 
    std::cout << "Inside try block" << std::endl;
    if (x > 0) // True
    { 
      throw x;// Following statement will be skipped
      std::cout << "After throw keyword" << std::endl;
    }
  } 
  catch (int x ) { 
    std::cout << "Inside catch block: Exception found" << std::endl;
  } 
  std::cout << "Outside try-catch block" << std::endl; 
}
Output:
Inside try block
Inside catch block: Exception found
Outside try-catch block

Exercise 2: Counting the Number of Times a Specific Number Appears in a Given List

In this exercise, we will discuss using the if statement and a for loop to count our magic number. Here, we will be trying to find all numbers that are divisible by 3, ranging from 1 to 30.

Note

To find out if a number is divisible by another, use the modulo (%) operator.

Now, let's perform the following steps:

  1. Import all the required header files:

    #include <iostream>
  2. We need to store the number of times a number is divisible by 3 in a counter. For this reason, we define and initialize the count variable to 0:

    unsigned count = 0;
  3. Now, we will use a for loop that produces values from 1 to 30 so that we can check whether they are divisible by 3 or not:

    for(unsigned x = 1; x <= 30; x++){
    }
  4. Finally, we will check in the body of the for loop by using an if statement and the expression x%3 == 0, which evaluates to true if the division has a remainder equal to 0:

    if (x%3 == 0) {
      count++;
    }
  5. If the previous condition returns to true, then the X variable is divisible by 3 and we can increment the counter.

  6. Finally, we can print count:

    std::cout << count << std::endl;

Bonus exercises:

  • Find how many numbers are divisible by 11 within the range of 1 to 100

  • Print all the numbers that are not divisible by 3 within the range of 1 to 30

Activity 1: Finding the Factors of 7 between 1 and 100 Using a while Loop

In the following activity, we will use a while loop and implement the previous concept from the earlier exercise to print the numbers between 1 and 100 that are divisible by 7.

Now, let's rewrite the previous code using a while loop in the following way:

  1. Create a variable of the unsigned type.

  2. Now, write the logic to print the numbers that are divisible by 7 using the while loop.

  3. Then, we have to increase the value of i after each iteration. Use the following code:

    i++;

Note

The solution for this activity can be found on page 282.

You have been reading a chapter from
C++ Fundamentals
Published in: Mar 2019
Publisher:
ISBN-13: 9781789801491
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image