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

Inheritance in c++

Hello friends, in this post today, we learn about Inheritance in c++ concept and types of inheritance in c++ . Which  is very important. so lets start... Inheritance  Inheritance   Class can acquire the properties and methods of another class. Inheritance is the process of deriving a new class from an already existing class. In other words" Inherit all the properties and methods of class into another class, is called Inheritance." Inheritance  provides the idea of reusability i.e., code once written can be used again and again in number  of new classes. The new class is called derived class and old class is called base class. The new class can use all or some of the features of the already existing  class and the programmer can define his own members to the new class. Types of Inheritance In c++, there are 5 types of inheritance. Types of Inheritance Syntax of Inheritance:- class derived_classname : access_spacifier base_classname Where class is keyword used to create a clas

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 derived  class . Constructor

What is scope resolution operator in c++

Hello friends, in this post today, we will learn about What is scope resolution operator in c++ and how to use in our program. so let's start.... Scope resolution operator  Scope resolution operator :- Scope resolution operator which is also known as ( membership lable ), represnted as (::) . The scope resolution operator is employed to resolve or extend the scope of variable or functions. C++ is block structured language. We know that the same variable or function name can be used to have different meaning in different block. The scope resolution operator will refer value of worldwide variable or function from anywhere (also from inner block). Without scope resolution operator all variable will refer local value. Example for variabe: #include   <iostream>   using   namespace   std ; int  m= 10 ; int   main () {       int  m= 20 ;      {       int  k=m;        int  m= 30 ;     cout<< "we are in inner block \n " ;      cout<< "k=" <<k<