0% found this document useful (0 votes)
4 views8 pages

Exception

The document explains exception handling in C++ using the keywords try, throw, and catch to manage errors that occur during code execution. It provides examples of expected and unexpected exceptions, detailing how to handle them and the consequences of uncaught exceptions. Additionally, it emphasizes the importance of resource management to prevent leaks when exceptions occur.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views8 pages

Exception

The document explains exception handling in C++ using the keywords try, throw, and catch to manage errors that occur during code execution. It provides examples of expected and unexpected exceptions, detailing how to handle them and the consequences of uncaught exceptions. Additionally, it emphasizes the importance of resource management to prevent leaks when exceptions occur.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

C++ Exceptions

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).

C++ try and catch


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:

Example

try{

// Block of code to try

throw exception; // Throw an exception when a problem arise

catch () {

// Block of code to handle errors


}

#include <iostream>

int main() {
int num1, num2, result;

std::cout << "Enter two numbers: ";


std::cin >> num1 >> num2;

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>

using namespace std;

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;
}

// Transfer funds to another account


void transferFunds(BankAccount &receiver, double amount) {
if (amount > balance) {
throw runtime_error("Insufficient funds for transfer!");
}
if (amount <= 0) {
throw invalid_argument("Transfer amount must be greater than zero!");
}

balance -= amount;
receiver.balance += amount;
cout << "Transfer Successful! Your New Balance: $" << balance << endl;
}

// Get account balance


double getBalance() const { return balance; }
};

// Derived class for specific account type


class SavingsAccount : public BankAccount {
public:
SavingsAccount(int accNo, double bal) : BankAccount(accNo, bal) {}
};

int main() {
try {
SavingsAccount customer1(101, 1000); // Account with $1000 balance
SavingsAccount customer2(102, 500); // Account with $500 balance

cout << "Customer 1 deposits $200..." << endl;


customer1.deposit(200);

cout << "\nCustomer 1 withdraws $500..." << endl;


customer1.withdraw(500);

cout << "\nCustomer 1 transfers $800 to Customer 2..." << endl;


customer1.transferFunds(customer2, 800); // This will cause an exception

} catch (const exception &e) {


cerr << "Transaction Failed: " << e.what() << endl;
}

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.

Case 1: Mismatched Exception Type (Pre-C++17 Style):

void myFunc() throw(int) { // says: I may only throw int


throw 'A'; // actually throws char
}

Case 2: Exception Not Caught by Any Catch Block:

try {
throw 3.14; // throws a double
} catch (int e) {
// This block does NOT handle double
cout << "Caught an int" << endl;
}

How C++ Handles Unexpected Exceptions:


In pre-C++17, you could use the set_unexpected() function to define a handler for
unexpected exceptions.

#include <iostream>
#include <exception>
using namespace std;

void myUnexpected() {
cout << "Unexpected exception occurred!" << endl;
exit(1);
}

void myFunc() throw(int) {


throw 'A';
}

int main() {
set_unexpected(myUnexpected); // register custom unexpected handler
try {
myFunc();
} catch (...) {
cout << "Caught something." << endl;
}
return 0;
}

What is an Uncaught Exception?


An uncaught exception in C++ is an exception that is thrown but not caught by any
catch block in the program. When this happens, the C++ runtime will call
std::terminate() and immediately stop the program.

Behavior of Uncaught Exceptions:


●​ Calls std::terminate() function.​

●​ std::terminate() by default ends the program immediately.​

●​ If noexcept function throws, and it's not caught → uncaught → terminate().

#include <iostream>
#include <string>
using namespace std;

void divide(int a, int b) {


if (b == 0) {
throw runtime_error("Division by zero!"); // throwing a standard exception
}
cout << "Result: " << (a / b) << endl;
}

int main() {
int x = 10, y = 0;

// Notice: NO try-catch block here


divide(x, y); // Will throw an exception

cout << "This line will not be executed." << endl;

return 0;
}

Uncaught Exception An exception that is thrown but not caught by any


catch block

Consequence Calls std::terminate(), and the program


terminates abruptly

Avoidance Always use try-catch, especially when calling


functions that may throw
Resource Capture and Release in the context of exceptions in
C++
When an exception is thrown, the normal flow of execution is interrupted. If
you've acquired resources (like memory, file handles, or database connections)
before the exception is thrown, and you don't release them properly, it can lead to
resource leaks.

🔥 Example: Resource Leak Without Proper Handling


#include <iostream>
#include <fstream>
using namespace std;

void writeToFile() {
ofstream file("example.txt"); // resource: file stream

file << "Writing to file..." << endl;

// Simulate an error
throw runtime_error("Some error occurred");

file << "This line will never execute" << endl;


// file.close(); // Never reached!
}

int main() {
writeToFile(); // No try-catch
return 0;
}

You might also like