Breaking News

BCA 3rd Sem: Object Oriented Programming Using C++ - Questions on Exception Handling

Q & A on Exception Handling

BCA 3rd Sem: Object Oriented Programming Using C++ - Questions on Exception Handling

Object Oriented Programming Using C++

Q1: Why is there need of raising exceptions when we can return errors?

Answer: There are scenarios when we do not have privilege of returning an error. e.g. memory allocation failure, hard disk failure or access violation. In case if an error is severe and further execution of program is impossible, program should raise an exception.

Q2: Explain Exception Handling mechanism using try/catch block?

Answer: In C++ exception handling is implemented using try/catch block. The statements that may generate an exception are placed in try block. The try block should not include those statements which cannot be executed once exception occurs. The try block is followed by one or more catch blocks. Catch block contains the exception handler code and catches the specific type of exception.

General syntax of try/catch block is:

     // statements
catch (datatype1 id1)
    // exception handling code
catch (datatype2 id2)
    // exception handling code

Q3: Give a C++ example showing exception handling in division by zero?


#include <iostream>
using namespace std;

int main( )
    int result, a, b;
    a = 12;
    b = 0;

    try {
         cout << "Dividing a by b = ";

         if (b == 0)
              throw 0;

         result = a / b;
         cout << "\n result = " << result << "\n";
    catch (int)
        cout <<  "Division by 0 exception" << endl;

     return 0;

Q4: Can a constructor throw an exception?

Answer: Yes. Constructors do not return errors. Exceptions are the best ways to inform bad construction.

Q5: What does catch (...) mean?

Answer: If the heading of a catch block contains...(ellipses) in place of parameters, then this catch block can catch exceptions of all types.

Q6: What exception is thrown by operator new id memory allocation fails?

Answer: bad_alloc

Q7: What happens if an exception is thrown, but not caught?

Answer: If there is no exception handler in the same function or parent functions, eventually program terminates.