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

'this' pointer in c++

Hello friends, i n this post today, we learn about 'this' pointer in c++ and what is the  use  of   'this'  pointer .  so lets start... this pointer in c++ 'this' pointer:- The this pointer is a special pointer which is a built-in pointer. and  'this' is a keyword. It stores the  address of current object in context. That is the current object which can be referred using this  pointer anywhere in the class. Important Points About this Pointer:- The this pointer can be used only inside the class i.e., only  inside the member function of the class and cannot be used outside and  static member of the class. The object’s address is available from within the member function as the this pointer. It  is legal, through unnecessary, to use this pointer when referring to members of the class. The  expression (*this) is commonly used to return the current object from a member function. this is a local object pointer in every instanc...

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

What is new and delete operator in c++

Hello friends, in this post today, we learn about What is new and delete operator in c++ . so lets start... new and delete operator  Memory Management Operators of C++:- The technique through which a program can obtain space in the RAM during the execution  of the program and not during compilation is called dynamic memory allocation. In this method space for the variables (array, strings, structure etc) is allocated from a free memory region which is known as heap.  For dynami c memory management, C++ provides two unary operator 'new' and 'delete'. Dynamic memory allocation is the allocation of memory at run time i.e., when program  executes then required memory is asked from the user and memory is allocated with the help of operator new. Syntax of new : data_type *ptr = new data_type; Here ptr is a variable of data_type. Memory is allocated by finding the size of data_type  automatically by the compiler and address of the allocated memory is returned which is ...