Exception Handling
Exception handling in C++ is a mechanism that enables elegant handling of anomalous situations and runtime faults to ensure the program can manage unexpected situations. C++ uses the try, throw and catch keywords to handle exceptions. Code in ‘try’ blocks has the potential to throw exceptions that are raised using `throw` instructions. and ‘catch’ blocks deal with exceptions thrown in the matching ‘try’ block.
Example:
The below example demonstrates the exception handling mechanism using try, throw and catch blocks
// C++ program to demonstrate exception handling
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
try {
// Declare and initialize two integers.
int x = 10, y = 0;
// Check if the divisor is zero.
if (y == 0)
// Throw a runtime error exception if divisor is
// zero.
throw runtime_error("Divide by zero error");
// Perform division and print the result (this line
// won't execute if y is zero).
cout << "Result: " << x / y << endl;
}
catch (const runtime_error& e) {
// Catch the runtime error exception and print the
// error message.
cout << "Exception caught: " << e.what() << endl;
}
return 0;
}
Output
Exception caught: Divide by zero error
7 Essential C++ Concepts for Every Developer
C++ is a powerful, high-performance programming language used in a wide range of applications, from game development to systems programming. To master C++, it’s crucial to understand some key concepts that form the foundation of this language. In this article, we will learn seven such essential C++ concepts that every developer should know.
Table of Content
- 1. Pointers
- 2. Object-Oriented Programming (OOP) Principles
- 3. Overloading
- 4. STL (Standard Template Library)
- 5. Memory Management
- 6. Exception Handling
- 7. Concurrency
Contact Us