Exception:
For example,
Dividing a number by zero.
a)Resumption- fix the problem and continue
b)Termination-Abort the process and return
In C++, the Resumption model is supported by the function call mechanism, and
the Termination model is supported by the exception-handling mechanism
Exception Handling:
“Exception Handling” allows us to manage the exception gracefully.
Using Exception Handling technique we can avoid abnormal termination of the program and continue with the normal flow or the program, or even move the control to other parts of the program.
Exceptions are handled using try catch statements.
General syntax:
try{
statements; . . . . .
}
catch(type1 arg){statements;}
catch(type2 arg){statements;}
•We can have more than one catch statement associated with a try.
Exception Handling Example:
#include<iostream.h> void main()
{
int j;
cin>>j;
try
int j;
cin>>j;
try
{
if(j==0) throw j;
int i=20/j;
}catch(int j){
cout<<"Divide by zero";
}catch(...){
cout<<"Caught Exception";
if(j==0) throw j;
int i=20/j;
}catch(int j){
cout<<"Divide by zero";
}catch(...){
cout<<"Caught Exception";
}
}
Divide by zero
Re-throwing an Exception:
A re-throw is indicated by a throw without an operand.
Example; try{
//code which throws error
}catch(Error e){
throw; //re-throw
}
If a re-throw is attempted when there is no exception to throw , terminate() will be called.
terminate(), by default, calls abort() to stop the program. But we can specify our own termination handler.
#include<string.h>
class MyException
{ char *msg;
public:
MyException(){
public:
MyException(){
msg="MyException";
}
MyException(char *m)
{
MyException(char *m)
{
msg=m;
}
char* getMessage(){
char* getMessage(){
return msg;
}
};
void main()
{
int age;
try{
cout<<"Enter your age";
cin>>age;
if(age>18)
cout<<"Ready to vote";
else{
MyException e("You are Minor!!");
throw e;
};
void main()
{
int age;
try{
cout<<"Enter your age";
cin>>age;
if(age>18)
cout<<"Ready to vote";
else{
MyException e("You are Minor!!");
throw e;
}
}
catch(MyException e)
{
cout<<"Exception"<<e.getMessage();
}
}
catch(MyException e)
{
cout<<"Exception"<<e.getMessage();
}
}
No comments:
Post a Comment