Exception Handling: Need of Exceptions, keywords, Simple and Multiple Exceptions| OOP in C++


Exception Handling


Exceptions are run-time anomalies or unusual conditions that a program may encounter.
Some anomalies are Divide By Zero, Accessing An Array Out of Its Bound etc. And Exception Handling is a method to handle those anomalies from occurring because these anomalies or unexpected errors can cause data loss.


Exception handling in c++ basically uses three keywords:
(a) try - In try block usually that code is written which may generate exception,
(example: expression in which divide by zero is present.etc). try block checks if the code can cause exception or not.
(b) throw - throw keyword is used in try block, which throws an exception at the time when exception occurs.
Example:
try{
if(x==0)
throw(x);
. . . . . . .
}
(c) catch - catch keyword is used to define catch block, which handles exception thrown by throw keyword from try block.
Program to demonstrate that try-throw-catch mechanism
This program throws the following
if x=0 then throws an int exception
if x=1 then throws a float exception
if x=2 then throws a char exception.

void test(int x)
{
try
{
if(x==0)
throw x;
else if (x==1)
throw 1.0;
else if(x==2)
throw 'z';
}
catch(int m)
{
cout<<"\n caught an integer exception";
}
catch(float n)
{
cout<<"\n caught a float exception";
}
catch(char c)
{
cout<<"\n caught a character exception";
}}
int main()
{
for(int i=0; i<=2; i++)
test(i);
}


Output:


Note:- To catch all types of exception the catch can be written as, catch(. . . .){}

Custom Search

%d bloggers like this: