In C++, an exception is a situation that arises during the execution of a program code. In C++ program, an exception is a response to an exceptional situation that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another part of the same program. Exception handling is built upon three keywords: try, throw and catch.
1. try: A try block in a program code, identifies that which particular exceptions will be activated and it followed by one or more catch blocks.
2. throw: A program code in C++, throws an exception when a problem shows up. This is done using a throw keyword.
3. catch: A program code in C++ catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword in the program code indicates the catching of an exception.
Assuming a block in C++ program code that will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows:
Syntex of the try/catch block:
try
{
// write your program code here
// throw an exception
}
catch( ExceptionName a )
{
// catch block program code
}
catch( ExceptionName b )
{
// catch block program code
}
catch( ExceptionName c )
{
// catch block program code
}
Program example on exception handling:
Programa 1:
Write a program in C++, which implement try/catch block.
#include<iostream>
using namespace std;
int main()
{
int c= 11;
try
{
throw c;
}
catch(int a)
{
cout << "An exception occurred!" << endl;
cout << "Exception number is: " << a << endl;
}
}
Output:
An exception occurred!
Exception number is: 11
Program example 2:
Write a program in C++, which implement try/catch block by implementing an error in try block and that particular exception is handled by the catch block.
#include<iostream>
using namespace std;
double division(int var1, int var2)
{
if (var2 == 0)
{
throw "Division by Zero.";
}
return (var1 / var2);
}
int main()
{
int x = 10;
int y = 0;
float z = 0;
try
{
z = division(x, y);
cout << z << endl;
}
catch (const char* abc)
{
cout << abc << endl;
}
return 0;
}
Output:
Division by Zero.
Post A Comment:
0 comments: