Skip to main content

Exception handling in c++

Hello friends, in this post today, we learn about What is exception handling  in c++ and how to handle exception in c++so lets start...

Exception handling in c++, Exception handling
Exception handling 



Exception handling:-

Exception is any abnormal behaviour. 

In C++ errors can be  two types.

1. Compile time errors and

2. Run time errors.

Compile time errors are syntax errors which occurs during the writing of the program. Most common examples of compile time errors are missing semicolon, missing comma, missing double quotes, etc.

The syntax error is detected during compilation of program, but the Run time  error will detect during execution of program. So, it is very difficult to handle logical error.


C++ provides exception handling mechanism which can be used to trap this exception and running programs smoothly after catching the exception.

The exception handling provides mechanism to handle logical error during execution of program with appropriate response.


Steps to handle Run time error:

1. Find the problem (Hit the exception) and write an exception in try block.

2. Inform that an error has occurred (Throw the exception)

3. Receive the error information (Catch the exception)

4. Take corrective actions (Handle the exception)


Exception Handling Mechanism:

This mechanism is built upon three keyword: try, throw and catch.

Try block

try is used to preface a block of statement which may generate exceptions. Whenever an exception is generated in the try block, it is thrown .An exception is an object so we can say that an exception object is thrown. The throw keyword is used for throwing an exceptionA try block must have at least one catch block.

Throw

Throw must be executed either within the try block proper or from any function that the code within the block calls.

catch block

A catch block is used to catches the exceptions thrown by throw statement and take appropriate action. catch block for catching different types of exceptions. A catch block must have a try block prior written which will throw an exception. If exception thrown  matches with the argument or object in the block, the statements written within the catch was caught successfully by the catch block .After the successful execution of the catch block statements any statements following the catch block will be executed. The relationship between try, throw and catch block is as shown in below figure.

Exception handling in c++, Exception handling
Exception handling 



Syntax:

try
{
statements;
statements;
statements;
throw exception;
}

catch (object or argument)
{
statements for handling the exception;
}


Example:

#include <iostream> 
using namespace std;

int main()
{
  int p,q;
  cout<<"Enter the value of p and q\n"cin>>p>>q;

try
{
 if(q!=0)
    cout<<"The result(p/q)="<<p/q
 else
 throw(q);
}

catch(int x)
{
 cout<<"Exception caught q="<<x;
}

return 0;
}

Output:

Enter the value of p and q
34
0
Exception caught q=0

When the value of q is zero at that time exception will throw and this exception will catch in catch block and print the message value is zero.


Multiple catch statements:-

It is possible that a program segment has more than one condition to throw an exception. For these situations we can put multiple catch blocks for a single try in case try block throws different types of exceptions.

When an exception is thrown, the exception handlers are searched in order for an appropriate match. The fist handler that yields a match is executed.

After executing the handler, the control goes to the first statement after the lat catch block for that try.

 Note: It is possible that arguments of several catch statements match the type of an exception.

In such cases, the first handler that matches the exception type is executed.


Example:

#include<iostream> 
using namespace std;

void test(int x)
{

try
{

if(x==1)
   throw(x);

else if(x==0)
   throw 'x';

else if(x==-1)
   throw 1.0;

}

catch(char c)
{
  cout<<"Caught a character"<<endl;
}

catch(int m)
{
  cout<<"Caught an integer"<<endl;
}

catch(float n)
{
  cout<<"Caught a double"<<endl;
}

cout<<"End of the try catch system"<<endl;
}

int main()
{
cout<<"Testing multiple catch"<<endl
cout<<"x==1"<<endl;

test(1);
cout<<"x==0"<<endl;
test(0);
cout<<"x==-1"<<endl
test(-1);
cout<<"x==2"<<endl
test(2);

return 0;
}

Output:-

Testing multiple catch
x==1
Caught an integer
End of the try catch system
x==0
Caught a character
End of the try catch system
x==-1


 Re-throwing an Exception:-

     A handler may decide to rethrow the exception caught without processing it.

     In such situations, we may simply invoke throw without any arguments as shown below:

throw;

     This causes the current exception to be thrown to the next enclosing try/catch sequence and is caught by a catch statement listed after that enclosing try block.

Example:

#include<iostream>
using namespace std;

void divide(double xdouble y)
{
  
  cout<<"Inside function \n"<<endl
  try
  {

   if (y==0
     throw y;
  
   else
    cout<<"Division ="<<x/y<<"\n";

  }

  catch(double)
 {
  cout<<"caught double inside the function \n"<<y<<endl;
  throw;
 }

  cout<<"End of function \n\n";
}

int main()
{

cout<<"Inside main"<<endl

try
{
divide(10.5,2.5);
divide(4,0);
}

catch(double)
{
  cout<<"caught double inside main \n"<<endl;
}

cout<<"End of main\n";

return 0;
}


Output:-

Inside main
Inside function 

Division =4.2
End of function 

Inside function 

caught double inside the function 
0
caught double inside main 

End of main



I hope that whatever information I have given in this post today, you have liked it and you have understood it.so keep learning and wait for the next post that will help you to increase your knowledge with the something new information.

Thank you so much for reading. And take care about yourself and your family.



Comments

Popular posts from this blog

Constructor in c++

Hello friends, in this post today, we learn about  what is constructor in c++ and types of constructor . so lets start... Constructor in c++ Constructor:-   A constructor is a “special” member function which initializes the objects of class.  Constructor is used to solve problem of initialization. Properties of constructor:- Constructors are used to construct the object of the class. Constructor name must be same as class name. Constructor is invoked automatically when objects of the class are created. The constructors are always declared in the public section. If declared in the private section then objects are can only be created inside the member functions but serve no purpose. It must be an instance member function , that is, it can never be static. Constructors  do not have any return type not even void so they cannot return any value. Constructor can also be overloaded. Constructors cannot be inherited, but they can be called from the constructors of...

What is reference variable in c++

Hello friends, in this post today, we learn about What is reference variable in c++. and what is its major use  in c++ . so lets start... Reference variable in c++ Reference variable:- Reference variable is a new concept in C++. A reference variable is a variable which provides an alias (alternative name) for a previously defined variable or any constant. Reference variable is an internal pointer. Declaration of reference variable is preceded with & symbol ( but do not read it as ‘address of ‘). Reference variable must be initialized during declaration. It can be initialized with already declared variables only. Reference variables can not be updated. This mechanism is useful in object oriented programming because it permits the manipulation of objects by reference, and eliminates the copying of object parameters back and forth. It is also important to note that references can be created not only for built-in data types but also for user- defined data types. Syntax: Data_...

Access modifiers in c++

Hello friends, in this post today, we will learn about Access modifiers in c++ and how to use it in data hiding. so let's start.... Access specifiers (or visibility labels)  that control the flow of data member and function outside the class. There are 3 types of access levels which are:- Access specifiers public: - Public is keyword . The class members ( functions or data) , which are declared as public can be accessed from outside the class. private:- Private members  of the class can only accessed by   the members functions with in that class. Private is a keyword which is used in Data hiding and Data abstraction. It is also used in Encapsulation. protected :- Protected is  keyword. This access specifier play a very important role in Inheritance. The class member s, which are declared as Protected   can be   accessed within the class   and   from derived class but cannot be accessed from any other class. NOTE :- If we do not declare any ...