Академический Документы
Профессиональный Документы
Культура Документы
Answer
Exception handling in C++ is implemented by using the try{} and catch(){} statements.
When a try block throws an exception, the program leaves the try block and enters the
catch statement of the catch block.
If they type of the object thrown matches the arg type in the catch block, catch block is
executed for handling the code.
When no exception is deteted or thrown then the control goes to the statement below the
catch block.
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.
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.
An exception which is of class type is known as Class Type Exception. The reason to
define a class type for an expression is to create an object that describes the error that
occurred. This information can be used by the exception handler to process the error. In
general, exception classes are created to encapsulate information about an error to enable
the exception handler to respond effectively.
Class MyException
{
public:
char str_exc[80];
int exc;
MyException()
{
*str_exc = 0;
exc = 0;
}
MyException(char*s, int e)
{
strcpy(str_exc, s);
exc = e;
}
};
int main()
{
int no;
try
{
cout << “Enter positive no:”;
cin >> no;
if (no <0)
throw MyException(“Not Positive”, no);
}
catch (MyExecption e)
{
cout << e.str_exc<<”: “<<e.exc <<”\n”;
}
return 0;
}
Sample run:
Enter positive No: -2
O/p: Not positive: -2
Thus, the program prompts the user for a positive no. If negative no is entered, an object
of the class MyException is created which encapsulates the information about the error.
#include <iostream>
using namespace std;
void MyHandler()
{
try
{
throw “hello”;
}
catch (const char*)
{
cout <<”Caught exception inside MyHandler\n”;
throw; //rethrow char* out of function
}
}
int main()
{
cout<< “Main start”;
try
{
MyHandler();
}
catch(const char*)
{
cout <<”Caught exception inside Main\n”;
}
cout << “Main end”;
return 0;
}
O/p:
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end
Thus, exception rethrown by the catch block inside MyHandler() is caught inside main();
<<Previous Next>>