Object Oriented Programming - Old Questions
9. How can you define catch statement that can catch any type of exception? Illustrate the use of multiple catch statement with example.
5 marks
|
Asked in 2076
The catch block defines the action to be taken, when an exception occur. We can use the catch statement with three dots as parameter (...) so that it can catch any types of exceptions. For example:
#include <iostream>
using namespace std;
void func(int a) {
try {
if(a==0) throw 23.33;
if(a==1) throw 's';
} catch(...) {
cout << "Caught Exception!\\n";
}
}
int main() {
func(0);
func(1);
return 0;
}
Multiple Catch Statements
Multiple catch statements are used when we have to catch a specific type of exception out of many possible type of exceptions i.e. an exception of type char or int or short or long etc. For 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.