Object Oriented Programming - Old Questions
11. Explain how exceptions are used for handling C++ error in a systematic and OOP-oriented way with the design that includes multiple exceptions.
5 marks
|
Asked in 2075
Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. Exception Handling in C++ is a process to handle runtime errors. We perform exception handling so the normal flow of the application can be maintained even after runtime errors. In C++, we use 3 keywords to perform exception handling: try, catch, and throw
- The
try
statement allows us to define a block of code to be tested for errors while it is being executed. - The
throw
keyword throws an exception when a problem is detected, which lets us create a custom error. - The
catch
statement allows us to define a block of code to be executed, if an error occurs in the try block.
Syntax to handle multiple exceptions:
try
{
//protected code
} catch(exceptionName e1)
{
// catch block
} catch(exceptionName e2)
{
// catch block
} catch(exceptionName en)
{
// catch block
}
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
int a=2;
try
{
if(a==1)
throw a; //throwing integer exception
else if(a==2)
throw 'A'; //throwing character exception
else if(a==3)
throw 4.5; //throwing float exception
}
catch(int a)
{
cout<<"\\nInteger exception caught.";
}
catch(char ch)
{
cout<<"\\nCharacter exception caught.";
}
catch(double d)
{
cout<<"\\nDouble exception caught.";
}
cout<<"\\nEnd of program.";
}
Output :
Character exception caught.
End of program.