Exception Handling in C++

Submitted by: 
Language: 

Exception Handling in C++

In this part you will learn:
1. What is an exception?
2. How using exception is useful?
3. How to use exception in a Program?
4. C++ syntax

What is exception?
In a class there arise many errors, depending upon the type of program handling these errors can be critically important sometimes. Exceptions is the way through which we handle the errors in a class using object oriented approach. Exceptions can occur due to many reasons like if the system has run out of memory or the object is initialized to impossible values. Most exceptions are used to handle system level errors(external errors)

How using exception is useful?
Exception handling is useful to identify such type of errors that cannot be handled by the program and also inform the user about it. We throw an exception normally when something is beyond the capability of the program which is not letting the program to execute properly.

How to use exception in a Program?

  1. class myclass {
  2. public:
  3. class AnError
  4. {};
  5. void Fun()
  6. {
  7. if (/*error condition*/)
  8. throw AnError();
  9. }
  10. };
  11. Int main()
  12. {try
  13. {
  14. //all code
  15. }
  16. Catch(myclass::Anerror)
  17. {
  18. //an error is displayed about the error.
  19. }
  20. }
  21. [/geshifilter-cpp]
  22. 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.
  23. 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.
  24. strong>Exceptions in C++
  25.  
  26. <strong>Basic Step:</strong>
  27. Open Dev C++ then File > new > source file and start writing the code below.
  28. [geshifilter-c]
  29. #include<stdio.h>
  30. #include<conio.h>
  31. #include<math.h>

style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-3664195971165750"
data-ad-slot="8323940646">

These are the header files that we need for coding. The main header is stdio.h which provides us with most of the functions for coding in C and the second header files is just for using a function which can pause the screen until the user hits any key.
In this program we will take user input about three attributes of employees user and in the end display all the information that was entered. We also displayed the largest most salary in the end of the program

  1. const int MAX=3;
  2. class Stack {
  3. int st[MAX];
  4. int top;
  5. public:
  6. class Range //exception class
  7. {};
  8. class Empty
  9. {};
  10. Stack() {top=-1;}
  11. void push(int var)
  12. {
  13. if (top >= MAX-1)
  14. throw Range();
  15. st[++top]=var;
  16. }
  17. int pop()
  18. {
  19. if (top<0)
  20. throw Empty();
  21. return st[top--];
  22. }
  23. };

In this part of the code we first have defined an integer type constant number MAX and initialized it to a value of 3. Then we have made a stack class in which we have two data members, default constructor and two member functions. Next we have declared two classes “Range” and “Empty” to check overflow and underflow of the stack respectively. Next we have initialized the value of top to -1 using default constructor. In the push function we have thrown an exception class “Range” which checks the overflow of the stack while in the pop function we have thrown an exception class “Empty” which checks the underflow of the stack, if any of the condition gets true an error message will popup.

  1. void main()
  2. {
  3. Stack s1;
  4. try
  5. { int a,b,c,d;
  6. cout<<"Enter the first number that you want to enter into the stack:";
  7. cin>>a;
  8. cout<<"\n Enter the second number that you want to enter into the stack:";
  9. cin>>b;
  10. cout<<"\n Enter the third number that you want to enter into the stack:";
  11. cin>>c;
  12. cout<<"\n Enter the fourth number that you want to enter into the stack:";
  13. cin>>d;
  14.  
  15. s1.push(a);
  16. s1.push(b);
  17. s1.push(c);
  18. s1.push(d); //stack got full
  19. cout<<s1.pop();
  20. cout<<s1.pop();
  21. cout<<s1.pop();
  22. cout<<s1.pop(); //stack is empty
  23.  
  24. }
  25. catch (Stack::Range) //we are handling exception here
  26. {
  27. cout<<"Exception: Stack Full"<<endl;
  28. }
  29. catch (Stack::Empty) //we are handling exception here
  30. {
  31. cout<<"Exception: Stack Empty"<<endl;
  32. }
  33.  
  34. cout<<"Here we exit the catch block"<<endl;
  35. }

In the main of the program we have divided our code into the try and catch block. In the try block we have simply written our code in which we take in the inputs and push the inputs into the stack. But as soon as we try to enter a number more than the capacity of the stack an error pops up and displayed on the screen.
The catch block is used to handle the errors. The error will be displayed if there is overflow and also if there is underflow. As soon as first error comes up the catch block is used and the compiler exits the main.
Execute > compile
then Execute > run
Output
output


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3>
  • You may insert videos with [video:URL]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.