EXCEPTION HANDLING
Introduction
Basic of Exception Handling
Its Mechanism
Throwing and Catching Mechanism
Rethrowing an Exception
Specifying Exception
4.
Program:1
#include<iostream>
using namespace std;
intmain()
{
int a=50,b=0,c;
c=a/b;
cout<<c<<endl;
return 0;
}
Output: Process returned -1073741676
NOTE: Error occur because of Logical Errors and Syntactic Errors.
But exception is because of RUNTIME ERROR, INVALID INPUT
ETC..
5.
INTRODUCTION
The process ofresponding to unwanted or unexpected events when a computer
program runs.
Exceptions are run time anomalies or unusual conditions that a program may encounter while
executing
detect and handle exceptions which are basically run time errors
It provides a type-safe, integrated approach, for coping with the unusual predictable problems that
arise while executing a program
Exceptions are of two kinds, namely, synchronous exceptions and asynchronous exceptions.
6.
BASIC EXCEPTION HANDLINGAND ITS MECHANISMS:
1. FIND THE PROBLEM (HIT THE EXCEPTION)
2. INFROM THAT AN ERROR HAS OCCURRED (THROW THE EXCEPTION)
3. RECEIVE THE ERROR INFORMATION (CATCH THE EXCEPTION)
4. TAKE CORRECTION ACTIONS (HANDLE THE EXCEPTION)
Exception handling mechanisms are of three keywords
namely try , throw and catch
TRY - GENERATE EXCEPTIONS
THROW - DECTECT AND THROW THE EXCEPTIONS
CATCH - CATCH THE EXCEPTION AND HANDLE
THE ERROR
try {
// Blockof code to try
throw exception; // Throw an exception
when a problem arise
}
catch () {
// Block of code to handle errors
}
SYNTAX:
9.
Program 2:
#include<iostream>
Using namespacestd;
int main()
{
int nume,deno,div;
cout<<“N Enter numerator and denominator:”
cin>>nume>>deno;
try
{
if(deno==0)
throw 0;
else
{
div=nume/deno;
cout<<“n BY DIVIDING”<<nume<<“and”<<deno<<“answer
is:”<<div;
}
}
catch(int num_exception)
{
cout<<“ n ERROR:CANNOT DIVIDE BY”<<num_exception<<endl;
}
return 0;
}
10.
OUTPUT:
Enter numerator anddenominator: 70 0
ERROR : CANNOT DIVIDE BY 0
OUTPUT:
Enter numerator and denominator: 70 7
BY DIVIDING 70 AND 7 ANSWER IS 10
throw point
function that causes an exception
Try block
Invokes a functions that contain an
exception
cCatch block
Catches and handles the exception
FUNCTION INVOKED BYTRY BLOCKTHROWING EXCEPTIONS:
11.
THROWING AND CATCHINGMECHANISM:
throw(exception);
throw exceptions;
throw; // used for rethrowing an exception
Catch(type arg)
{
//statement block for managing
exception
}
MULTIPLE CATCHING STATEMENTS:
Try
{ //try block }
catch(type1 arg)
{ //catchblock1 }
catch(type2 arg)
{ //catchblock2 }
----------
----------
12.
Program 4:
#include<iostream>
Using namespacestd;
Void test(int x)
{
try
{
if(x==1)
throw x;
else
{
if(x==0)
throw ‘x’;
else
{
if(x== -1)
throw 2.5;
}
}
}
Catch(char c)
{
cout<<“caught a
character “;
}
catch(int x)
{
cout<<“caught a
integer”;
}
catch(float d)
{
cout<<“caught a
floating value”;
}
}