Q11. Define exception and explain about exception handling.
Answer:
Exception
An exception is a run time error that occurs while executing a program. The run time errors might be conditions such as division by zero, access to an array out of bounds, running out of memory or disk space etc. These exceptions should be handled correctly otherwise, the program terminates abnormally.
Exception Handling
Exception handling in C++ handles only synchronous exceptions. C++ exception handling mechanism uses three keywords: try, catch and throw. The block of statements that may throw exceptions are put inside the try block. When an exception is detected, it is thrown using a throw statement in the try block. The exceptions generated in try block and thrown using throw statement are caught and handled in the catch block.
When the try block throws an exception then the control leaves the try block and goes to the catch block. Exceptions are nothing but the objects that are used to transmit information about a problem. If exception thrown matches the argument type in the catch block then the catch block is executed which reports the error. If exception thrown does not match the argument type in the catch block then the program is aborted by default using abort() function. If no exception is thrown in the try block then the control goes to next statement immediately following the catch block by skipping the catch block.
Example
The following example illustrates the mechanism of exception handling.
#include<iostrearn>
using namespace std;
int main()
int a, b, c;
cout <<"Enter a and b values:";
cin >> a >>b;
if (b == 0)
try
{
if (b == 0) throw b;
else
cout <<"c="<<a/b,
}
catch(int x)
{
cout<<"Error: Divide by Zero exception\n";
}
return 0;
}
Output