C++ Exception Handling
C++ Exception Handling
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
}
catch( ExceptionName e2 ) {
// catch block
}
catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
different situations.
Throwing Exceptions
Exceptions can be thrown anywhere within a code block
using throw statement. The operand of the throw statement determines a
type for the exception and can be any expression and the type of the result
of the expression determines the type of exception thrown.
Catching Exceptions
The catch block following the try block catches any exception. You can
specify what type of exception you want to catch and this is determined by
the exception declaration that appears in parentheses following the keyword
catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception
and we catch it in catch block.
// program to divide two numbers throws an exception when the divisor is 0
#include <iostream>
using namespace std;
int main() {
double numerator, denominator, divide;
cout << "Enter numerator: ";
cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;
try {
// throw an exception if denominator is 0
if (denominator == 0)
throw 0;
// not executed if denominator is 0
divide = numerator / denominator;
cout << numerator << " / " << denominator << " = " << divide <<
endl;
}
catch (int num_exception) {
cout << "Error: Cannot divide by " << num_exception << endl;
}
return 0;
}
return 0;
}
#include <iostream>
#include <stdexcept> // For runtime_error
using namespace std;
int main() {
double numerator, denominator, divide;
cout << "Enter numerator: ";
cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;
try {
// Throw an exception if denominator is 0
if (denominator == 0)
throw runtime_error("Division by zero is not allowed");
divide = numerator / denominator;
cout << numerator << " / " << denominator << " = " << divide
<< endl;
}
catch (const runtime_error& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
Output :
Enter numerator: 10
Enter denominator: 0
ERROR!
Error: Division by zero is not allowed
e.what() in C++ Exception Handling
In C++, e.what() is a member function of the std::exception class (and its
derived classes like std::runtime_error). It returns a descriptive error
message when an exception is thrown. When an exception is caught, calling
e.what() gives us a human-readable string describing the error.
Example:1
#include <iostream>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}
Example:2
#include <iostream>
#include <stdexcept> // For standard exception classes
using namespace std;
int main() {
try {
int age;
cout << "Enter your age: ";
if (!(cin >> age)) { // Check if input is non-numeric
throw invalid_argument("Error: Non-numeric input
entered.");
}
if (age < 0) {
throw out_of_range("Error: Age cannot be negative.");
}
if (age < 18) {
throw runtime_error("Access denied - You must be at
least 18 years old.");
}
cout << "Access granted - You are old enough." << endl;
}
catch (const invalid_argument& e) {
cout << "Invalid Input: " << e.what() << endl;
}
catch (const out_of_range& e) {
cout << "Invalid Age: " << e.what() << endl;
}
catch (const runtime_error& e) {
cout << "Restriction: " << e.what() << endl;
}
catch (const exception& e) {
cout << "An unexpected error occurred: " << e.what() <<
endl;
}
return 0;
}
Properties of Exception Handling in C++
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 (…) {
cout << "Access denied - You must be at least 18 years old.\n";
}
return 0;
}
int main()
{
try {
throw ‘a’;
}
catch (int x) {
cout << "Caught " << x;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught ";
}
return 0;
}
in C++, try/catch blocks can be nested. Also, an exception can be
re-thrown using “throw; “.
// C++ program to demonstrate try/catch blocks can be nested
in C++
#include <iostream>
using namespace std;
int main()
{
// nesting of try/catch
try {
try {
throw 20;
}
catch (int n) {
cout << "Handle Partially ";
throw; // Re-throwing an exception
}
}
catch (int n) {
cout << "Handle remaining ";
}
return 0;
}
When an exception is thrown, all objects created inside the
enclosing try block are destroyed before the control is transferred
to the catch block.
#include <iostream>
using namespace std;
int main()
{
try {
// Create an object of class Test
Test t1;