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...

Function with Default arguments in c++

Hello friends, i n this post today, we learn about   Function with Default arguments in c++ .  so lets start... Function with default arguments  Function with default arguments:- In C ++ it is possible for a function not to specify all its arguments. Some of the arguments  may be specified their default values at the time of declaring the function.   Default values are specified when the function is declared. We must add default arguments from right to left. We cannot provide a default value to a particular argument in the middle of an argument list. Default arguments are useful in situations where some arguments always have the same value. For Example, passing marks. In a function with default argument, if one argument is default, all successive arguments  must be default. We cannot provide default values in the middle of the arguments or towards  l eft side. We provide few examples: 1. void fun(int x, int y = 20, int z=35); (valid) 2. void fun(int x,...

function overriding in c++

Hello friends, i n this post today, we learn about w hat is function overriding  in c++ .  so lets start... Function overriding in c++ Function overriding:- In function overriding we write the same function which is defined in base class, we write the same function in derived class with same parameter is known as function overriding.  If base class and derived class have member functions with same name and arguments.  If you create an object of derived class and write code to access that member function then, the member function in derived class is only invokes. Means the member function of derived class overrides the member function of base class. This is called function overriding or method overriding in C++. Example: //Function overriding #include <iostream>   using   namespace   std ; class   A {    public:    void   display ()   {     cout << "This is parent ...