class myclass { public: class AnError {}; void Fun() { if (/*error condition*/) throw AnError(); } }; Int main() {try { //all code } Catch(myclass::Anerror) { //an error is displayed about the error. } } [/geshifilter-cpp] In the above code it is demonstrated how to use the exceptions in the function, it must be noted here that “throw”, “catch” and “try” are the keywords here. Whenever we use exceptions in a program, we first have to declare a class for an error inside our class and then in the function whenever an error condition comes up we simply use that error class to display an error, we do this by using throw key word as shown above. In the main of the program we write code in the try block and part which is considered to have an error is placed in the catch block in which error class is used by using binary scope resolution as shown above. strong>Exceptions in C++ <strong>Basic Step:</strong> Open Dev C++ then File > new > source file and start writing the code below. [geshifilter-c] #include<stdio.h> #include<conio.h> #include<math.h>
const int MAX=3; class Stack { int st[MAX]; int top; public: class Range //exception class {}; class Empty {}; Stack() {top=-1;} void push(int var) { if (top >= MAX-1) throw Range(); st[++top]=var; } int pop() { if (top<0) throw Empty(); return st[top--]; } };
void main() { Stack s1; try { int a,b,c,d; cout<<"Enter the first number that you want to enter into the stack:"; cin>>a; cout<<"\n Enter the second number that you want to enter into the stack:"; cin>>b; cout<<"\n Enter the third number that you want to enter into the stack:"; cin>>c; cout<<"\n Enter the fourth number that you want to enter into the stack:"; cin>>d; s1.push(a); s1.push(b); s1.push(c); s1.push(d); //stack got full cout<<s1.pop(); cout<<s1.pop(); cout<<s1.pop(); cout<<s1.pop(); //stack is empty } catch (Stack::Range) //we are handling exception here { cout<<"Exception: Stack Full"<<endl; } catch (Stack::Empty) //we are handling exception here { cout<<"Exception: Stack Empty"<<endl; } cout<<"Here we exit the catch block"<<endl; }