Exception
Exception
When executing C++ code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message.
The technical term for this is: C++ will throw an exception(throw an error).
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.
Example
try{
catch () {
#include <iostream>
int main() {
int num1, num2, result;
try {
if (num2 == 0) {
throw "Error: Division by zero is not allowed!";
}
result = num1 / num2;
std::cout << "Result: " << result << std::endl;
} catch (const char* msg) {
std::cerr << msg << std::endl;
}
return 0;
}
#include <iostream>
#include <stdexcept>
class BankAccount {
protected:
int accountNumber;
double balance;
public:
BankAccount(int accNo, double bal) : accountNumber(accNo), balance(bal) {}
// Deposit money
void deposit(double amount) {
if (amount <= 0) {
throw invalid_argument("Deposit amount must be greater than zero!");
}
balance += amount;
cout << "Deposit Successful! New Balance: $" << balance << endl;
}
// Withdraw money
void withdraw(double amount) {
if (amount > balance) {
throw runtime_error("Insufficient funds for withdrawal!");
}
if (amount <= 0) {
throw invalid_argument("Withdrawal amount must be greater than zero!");
}
balance -= amount;
cout << "Withdrawal Successful! New Balance: $" << balance << endl;
}
balance -= amount;
receiver.balance += amount;
cout << "Transfer Successful! Your New Balance: $" << balance << endl;
}
int main() {
try {
SavingsAccount customer1(101, 1000); // Account with $1000 balance
SavingsAccount customer2(102, 500); // Account with $500 balance
return 0;
}
Expected Exceptions:
These are exceptions that the programmer anticipates and handles using try-catch blocks.
They usually arise from known error conditions like invalid input, file not found, divide by
zero, etc.
🔹 Example:
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 0;
try {
if (b == 0)
throw "Divide by zero error!";
cout << a / b;
} catch (const char* msg) {
cout << "Expected Exception Caught: " << msg << endl;
}
return 0;
}
Unexpected Exceptions:
An unexpected exception occurs when a function throws an exception not listed in its
exception specification (in older versions of C++), or when an exception is thrown and not
caught by any handler in the program.
try {
throw 3.14; // throws a double
} catch (int e) {
// This block does NOT handle double
cout << "Caught an int" << endl;
}
#include <iostream>
#include <exception>
using namespace std;
void myUnexpected() {
cout << "Unexpected exception occurred!" << endl;
exit(1);
}
int main() {
set_unexpected(myUnexpected); // register custom unexpected handler
try {
myFunc();
} catch (...) {
cout << "Caught something." << endl;
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
int x = 10, y = 0;
return 0;
}
void writeToFile() {
ofstream file("example.txt"); // resource: file stream
// Simulate an error
throw runtime_error("Some error occurred");
int main() {
writeToFile(); // No try-catch
return 0;
}