Exception Handling in C++
try
: This is used to specify a section of the code where a problem might occur and we want to handle it.catch
: This is used to handle the problem that was thrown.throw
: This is used when a problem occurs in the program.
#include <iostream>
using namespace std;
// function to throw division by zero exception
void divide(int num, int den) {
if (den == 0) {
throw runtime_error("Division by zero error");
}
cout << "Result of division: " << num / den << endl;
}
int main() {
int numerator = 5, denominator = 0;
try {
divide(numerator, denominator);
} catch (const exception& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
Output
Error: Division by zero error
Exception Handling in Programming
Exception handling is a critical aspect of programming, enabling developers to manage unexpected or erroneous situations gracefully. In this article, we’ll discuss the concept of exception handling, its importance, and best practices for implementing it effectively in various programming languages.
Table of Content
- What is Exception Handling?
- Components of Exception Handling
- Exception Handling in C
- Exception Handling in C++
- Exception Handling in Java
- Exception Handling in Python
- Exception Handling in C#
- Exception Handling in JavaScript
- Exception Handling Best Practices