18.6 OBJECT AS EXCEPTION

We have said that exceptions can be objects. Let us try a simple program.

Problem: Write a program to demonstrate throwing an object as exception.

Solution: First, we will create a simple class named myException. Then we will throw an object of this class. This object will be created only at the time of throwing an exception. See Program 18.3.

Program 18.3 Object as exception

// excep5.cpp#include<iostream>using namespace std;class myException{ public:  int key ;   myException() { key = 4 ;};   void show()      { cout << “key is ” << key << endl ;      };} ;int main(){  int i=3,j=0,k =3;   cout<< “<---excep5.cpp--- >” << endl ;   try     { if ( j == 0) throw new myException() ;       k = i / j ;       cout << k << ...

Get Object Oriented Programming with C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.