C++ Exception Handling Question:
Download Job Interview Questions and Answers PDF
Explain Exception handling for a class with an example?
Answer:
Exceptions are certain disastrous error conditions that occur during the execution of a program. They could be errors that cause the programs to fail or certain conditions that lead to errors. If these run time errors are not handled by the program, OS handles them and program terminates abruptly, which is not good.
To avoid this, C++ provides Exception Handling mechanism.
The three keywords for Exception Handling are:
Try, Catch and Throw.
The program tries to do something. If it encounters some problem, it throws an exception to another program block which catches the exception.
Ex:
void main()
{
int no1, no2;
try
{
cout << “Enter two nos:”;
cin >> no1 >> no2;
if (no2 == 0)
throw “Divide by zero”;
else
throw no1/no2;
}
catch (char *s)
{
cout << s;
}
catch (int ans)
{
cout << ans;
}
}
We know that divide by zero is an exception. If user enters second no as zero, the program throws an exception, which is caught and an error message is printed else the answer is printed.
To avoid this, C++ provides Exception Handling mechanism.
The three keywords for Exception Handling are:
Try, Catch and Throw.
The program tries to do something. If it encounters some problem, it throws an exception to another program block which catches the exception.
Ex:
void main()
{
int no1, no2;
try
{
cout << “Enter two nos:”;
cin >> no1 >> no2;
if (no2 == 0)
throw “Divide by zero”;
else
throw no1/no2;
}
catch (char *s)
{
cout << s;
}
catch (int ans)
{
cout << ans;
}
}
We know that divide by zero is an exception. If user enters second no as zero, the program throws an exception, which is caught and an error message is printed else the answer is printed.
Download C++ Exception Handling Interview Questions And Answers
PDF
Previous Question | Next Question |
Can you please Illustrate Rethrowing exceptions? | Describe exceptions in C++? |