#include <iostream>
#include <stdexcept>
// Base class
class Shape {
public:
virtual void draw() const = 0; // Virtual function for drawing
virtual void handleException() const {
throw std::runtime_error("Exception in base class Shape!");
}
};
// Derived class - Circle
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing Circle..." << std::endl;
}
void handleException() const override {
throw std::runtime_error("Exception in Circle class!");
}
};
// Derived class - Square
class Square : public Shape {
public:
void draw() const override {
std::cout << "Drawing Square..." << std::endl;
}
void handleException() const override {
throw std::runtime_error("Exception in Square class!");
}
};
int main() {
try {
Shape* shapes[] = {new Circle(), new Square()};
for (const auto& shape : shapes) {
shape->draw();
shape->handleException(); // Call virtual function for exception handling
}
// Clean up objects
for (const auto& shape : shapes) {
delete shape;
}
} catch (std::exception& ex) {
std::cout << "Exception caught: " << ex.what() << std::endl;
}
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: