C++ Exception Handling

In this C++ tutorial, let us see the Exception Handling in C++, types of exceptions and sample programs to understand the concepts better.

Exception signifies something wrong. Any error in the program that is encountered while the code is executing is known as an exception.
Suppose, the code accepts two numbers from the user, i.e. x and y.
Now, the code writes the following line
z=x/y
If the user has entered 0 as the value of y, a “DivideByZero” error is encountered. This is an exception.

Types of Exceptions in C++

Synchronous

Exception whose source is the throw statement.
E.g. Array range out of bounds, overflow exceptions, division by zero, etc. C++ supports only these exceptions.

Asynchronous

Errors that the program cannot candle are known as asynchronous exceptions.
E.g. keyboard interrupts
These exceptions are caused by the events that happen outside the flow of the program.

Keywords

Normally, exceptions are handled in C++, using the following keywords:

try

Consists of a set of statements that may be the source of error. E.g. if the code consists of two variables, a & b, assuming both take input from user & the code tries to find out the value of c as c=a/b.
if the user provides the value 0 to b, then the above statement will generate run time error “divide by 0”. So, this is the ideal candidate for the set of statements that make up try block.

throw

A detected exception is thrown using throw statement in try block.

catch

This statement catches the exception that the throw statement
has thrown in the try block. The catch statement catches the exception accordingly.

C++ Exception Handling Program

This program tries to trace divide by zero error.

#include<iostream.h>
void main()
{
int x,y,z;
try
{
cout<<"Enter two numbers : ";
cin>>x>>y;
z=x/y;
cout<<"\nThe result = "<<z;
}
catch(int i)
{
cout<<"\nException "<<i;
}
cout<<"\nThe program ends\n";
}

Output

Enter 1 1
The result = 1
The program ends

Leave a Comment

Your email address will not be published. Required fields are marked *