1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M10 Try Catch
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
10Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M10 Try Catch

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
10Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Try/Catch

Overview

If a function throws an Exception, and it hits the main() scope uncaught, the program dies. To prevent this, we use a Try/Catch Block.

You wrap any dangerous, unpredictable code inside the try { } block. This tells the C++ runtime to 'monitor' this code. If an exception is thrown inside the try block (even if it's deeply nested 10 functions down), the execution instantly halts, abandons the try block, and teleports directly into the matching catch { } block. Here, you can safely log the error, alert the user, and allow the program to continue running normally.

Syntax

cpp
#include <iostream>

void riskyFunction(bool fail) {
    if (fail) throw "Database Offline!";
    std::cout << "Processing data...\n";
}

int main() {
    // 1. TRY BLOCK: Monitor this code for explosions
    try {
        riskyFunction(true); 
        std::cout << "This line will NEVER print because an error was thrown above!\n";
    } 
    // 2. CATCH BLOCK: The safety net
    // It catches the specific data type thrown (a string/char pointer)
    catch (const char* errorMessage) {
        std::cout << "Intercepted an Error: " << errorMessage << "\n";
    }
    
    // 3. SURVIVAL
    std::cout << "The program survived and is continuing normally!\n";
    return 0;
}

Common Pitfalls

  • Catching by Value instead of Reference. If an exception throws a massive Custom Error Object, writing catch (CustomError e) physically copies the entire object in RAM. You should ALWAYS write catch (const CustomError& e) to catch it by Reference, saving memory and preventing 'Object Slicing' issues.

Interview Questions

Can you have multiple catch blocks for a single try block?

Yes. A try block can be followed by an infinite chain of catch blocks, each designed to catch a different data type (e.g., catch(int), catch(string), catch(NetworkError)). The compiler will mathematically evaluate them top-to-bottom and execute the first one that perfectly matches the thrown data type.

Real-World Example

Using chained Catch blocks to handle completely different types of system failures gracefully.

example
cpp
#include <iostream>

void parseData(int dataCode) {
    if (dataCode == 1) throw 404;                     // Throws an int
    if (dataCode == 2) throw "Corrupted Payload";     // Throws a string
}

int main() {
    try {
        parseData(1);
    } 
    catch (int errorCode) {
        std::cout << "HTTP Error: " << errorCode << "\n";
    } 
    catch (const char* msg) {
        std::cout << "Data Error: " << msg << "\n";
    }
    return 0;
}

Check Your Knowledge

Test your understanding of Try/Catch with these quick questions.

Question 1

What happens to the remaining code inside a `try` block immediately after an exception is thrown?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Try/Catch

Overview

If a function throws an Exception, and it hits the main() scope uncaught, the program dies. To prevent this, we use a Try/Catch Block.

You wrap any dangerous, unpredictable code inside the try { } block. This tells the C++ runtime to 'monitor' this code. If an exception is thrown inside the try block (even if it's deeply nested 10 functions down), the execution instantly halts, abandons the try block, and teleports directly into the matching catch { } block. Here, you can safely log the error, alert the user, and allow the program to continue running normally.

Syntax

cpp
#include <iostream>

void riskyFunction(bool fail) {
    if (fail) throw "Database Offline!";
    std::cout << "Processing data...\n";
}

int main() {
    // 1. TRY BLOCK: Monitor this code for explosions
    try {
        riskyFunction(true); 
        std::cout << "This line will NEVER print because an error was thrown above!\n";
    } 
    // 2. CATCH BLOCK: The safety net
    // It catches the specific data type thrown (a string/char pointer)
    catch (const char* errorMessage) {
        std::cout << "Intercepted an Error: " << errorMessage << "\n";
    }
    
    // 3. SURVIVAL
    std::cout << "The program survived and is continuing normally!\n";
    return 0;
}

Common Pitfalls

  • Catching by Value instead of Reference. If an exception throws a massive Custom Error Object, writing catch (CustomError e) physically copies the entire object in RAM. You should ALWAYS write catch (const CustomError& e) to catch it by Reference, saving memory and preventing 'Object Slicing' issues.

Interview Questions

Can you have multiple catch blocks for a single try block?

Yes. A try block can be followed by an infinite chain of catch blocks, each designed to catch a different data type (e.g., catch(int), catch(string), catch(NetworkError)). The compiler will mathematically evaluate them top-to-bottom and execute the first one that perfectly matches the thrown data type.

Real-World Example

Using chained Catch blocks to handle completely different types of system failures gracefully.

example
cpp
#include <iostream>

void parseData(int dataCode) {
    if (dataCode == 1) throw 404;                     // Throws an int
    if (dataCode == 2) throw "Corrupted Payload";     // Throws a string
}

int main() {
    try {
        parseData(1);
    } 
    catch (int errorCode) {
        std::cout << "HTTP Error: " << errorCode << "\n";
    } 
    catch (const char* msg) {
        std::cout << "Data Error: " << msg << "\n";
    }
    return 0;
}

Check Your Knowledge

Test your understanding of Try/Catch with these quick questions.

Question 1

What happens to the remaining code inside a `try` block immediately after an exception is thrown?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A