Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Blocks in Objective-C
Next article icon

Nested Try Blocks in C++

Last Updated : 28 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, a nested try block refers to the try-block nested inside another try or catch block. It is used to handle exceptions in cases where different exceptions occur in a different part of the code.

Syntax of Nested Try Blocks

The nested try/catch takes this syntax:

try  {      // Code...... throw e2      try      {          // code..... throw e1      }      catch (Exception e1)      {          // handling exception      }  }  catch (Exception e2)  {          // handling exception  }

Here,

  • e1: Exception thrown in inner block.
  • e2: Exception thrown in outer block.

Example of Nested Try Blocks

C++
// C++ program to illustrate the use of nested try blocks #include <iostream> using namespace std;  // function throwing exceptions void func(int n) {     if (n < 10) {         throw 22;     }     else {         throw 'c';     } }  // driver code int main() {     try {         try {             cout << "Throwing exception from inner try "                     "block\n";             func(2);         }         catch (int n) {             cout << "Inner Catch Block caught the exception"                  << endl;         }     }     catch (char c) {         cout << "Outer catch block caught the exception"              << endl;     }      cout << "Out of the block";      return 0; } 

Output
Throwing exception from inner try block  Inner Catch Block caught the exception  Out of the block

Explanation

Here, we used func() function to throw two exceptions of int and char type. We used an inner try block to catch integer exceptions. Now, whenever the try blocks throw an exception, the control moves outwards from the nested block till the matching catch block is found. In this case, it was the inner catch block that caught the exception.

What happens if we throw a character exception that the outer catch block is programmed to handle? Let's see,

C++
// C++ program to illustrate the use of nested try blocks #include <iostream> using namespace std;  // function throwing exceptions void func(int n) {     if (n < 10) {         throw 22;     }     else {         throw 'c';     } }  // driver code int main() {     try {         try {             cout << "Throwing exception from inner try "                     "block\n";             func(12);         }         catch (int n) {             cout << "Inner Catch Block caught the exception"                  << endl;         }     }     catch (char c) {         cout << "Outer catch block caught the exception"              << endl;     }      cout << "Out of the block";      return 0; } 

Output
Throwing exception from inner try block  Outer catch block caught the exception  Out of the block

Here, the outer catch block caught the exception as expected.

The try blocks can also be the nested in the catch block in a similar way.


Next Article
Blocks in Objective-C
author
rohitsharma_26
Improve
Article Tags :
  • C++
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • CPP

Similar Reads

  • Blocks in Objective-C
    Blocks in Objective-C are a potent tool that can simplify the development process. Blocks are an alternative to traditional functions, allowing you to write code that is more concise and efficient. They are used for many different purposes, including as callbacks and iterators. Blocks can also be us
    6 min read
  • Nested if in C++
    If is a type of condition checking in which a condition turns out to be true a block of statements is executed. Syntax: // if base_condition is true // every inside the { } block will be executed if (base_condition) { statement 1............... statement 2 .............. } Example C/C++ Code // C++
    3 min read
  • Try and Catch Block in MATLAB
    Exception Handling is a mechanism used to resolve/handle Runtime errors that arise during the execution of a program. Most programming languages offer some level of exception handling to deal with errors that arise while the program is executing. Exception handling deals with these events to avoid t
    3 min read
  • Nested Classes in C++
    A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed. For example, p
    1 min read
  • Try Catch Block in Programming
    In programming, a try catch block is used for exception handling. The try block contains code that might throw an exception and the catch block handles specific exceptions by providing custom code. It prevents program termination when exceptions occur. Remember, we can use a try block without a catc
    7 min read
  • islessgreater() in C/C++
    In C++, islessgreater() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions.islessgreater() function is used to check whether the 1st argument given to the function is less than or greater than the 2nd argument given to t
    3 min read
  • std::lower_bound in C++
    In C++, the std::lower_bound() is a built-in function used to find the position of an element in a sorted range that has a value not less than the given value. It is defined inside the <algorithm> header file. In this article, we will learn about std::lower_bound() function in C++. Example: [G
    7 min read
  • C++ Nested if-else Statement
    Nested if-else statements are those statements in which there is an if statement inside another if else. We use nested if-else statements when we want to implement multilayer conditions (condition inside the condition inside the condition and so on). C++ allows any number of nesting levels. Let's ta
    3 min read
  • std::binary_search() in C++ STL
    In C++, STL provide std::binary_search() function which implements binary search algorithm to check whether an element exists in the given sorted range. It is defined inside <algorithm> header file. In this article, we will learn about std::binary_search() function in C++. Example: [GFGTABS] C
    3 min read
  • Nested Loops in C++ with Examples
    Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as "loop inside loop". Syntax for Nested For loop: for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of inside loop } // statement of ou
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences