C++ Exception Handling C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
C++ Exception Handling
C++ Exception Handling
Exception handling in C++ consist of three keywords: try
, throw
and catch
:
The try
statement allows you to define a block of code to be tested for errors while it is being executed.
The throw
keyword throws an exception when a problem is detected, which lets us create a custom error.
The catch
statement allows you to define a block of code to be executed if an error occurs in the try block.
The try
and catch
keywords come in pairs:
Syntax
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
You can also use the throw
keyword to output a reference number, like a custom error number/code for organizing purposes.
Example
#include <iostream>
using namespace std;int main() {
try {
int age = 15;
if (age > 18) {
cout << "Access granted - you are old enough.";
} else {
throw 505;
}
}
catch (int myNum) { //myNum is 505 which is thrown by throw keyword in above try block
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Error number: " << myNum;
}
return 0;
}
Output:
Access denied - You must be at least 18 years old.
Error number: 505