Exception Handling in C++

Advertisements

Prev Tutorial Next Tutorial

Exception Handling in C++

The process of converting system error messages into user friendly error message is known as Exception handling. This is one of the powerful feature of C++ to handle run time error and maintain normal flow of C++ application.

Exception

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's Instructions.

Handling the Exception

Handling the exception is nothing but converting system error message into user friendly error message. Use Three keywords for Handling the Exception in C++ Language, they are;

  1. try
  2. catch
  3. throw

Syntax for handling the exception

Example of Exception Handling in C++

try
{
   // causes executions code
}
catch( ExceptionName e1 )
{
   // catch block
}
catch( ExceptionName e2 )
{
   // catch block
}
catch( ExceptionName eN )
{
   // catch block
}

Try Block

It is one of the block in which we write the block of statements which causes executions at run time in other words try block always contains problematic statements.

Catch block

It is one of the block in which we write the block of statements which will generates user friendly error messages in other words catch block will suppose system error messages.

Example without Exception Handling

Example

#include<iostream.h>
#include<conio.h>

void main() 
{
int a, ans;
a=10;
ans=a/0;
cout<<"Result: "<<ans;
}

Output

Abnormally terminate program

Example of Exception Handling

Example

#include<iostream.h>
#include<conio.h>

void main() 
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch(int i)
{
cout<<"Denominator not be zero";
}	
}

Output

Denominator not be zero

Prev Tutorial Next Tutorial

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements