By: Pn. Nor Anisah Binti Mohd Saad
By: Pn. Nor Anisah Binti Mohd Saad
CHAPTER 4
EXCEPTION HANDLING
By:
PN. NOR ANISAH BINTI MOHD SAAD
CHAPTER 4.0 : EXCEPTION HANDLING
A
Concept of exception handling
B
Try, Throw and Catch
C
Standard Library Exception
D
Examples
A CONCEPT OF EXCEPTION HANDLING
V. Arithmetic overflow
try
{
DangerousStatement
throw exception();
}
catch(<exception_class> <object>)
{
//perform error processing
}
B TRY, THROW AND CATCH (CONT.)
2. try block are created to surround areas of code that might have a problem.
A try block is a block, surrounded by braces, in which an exception might
be thrown. An exception is thrown by using the throw keyword inside the
try block.
try
{
DangerousStatement
throw exception();
}
3. A catch block is the block immediately following a try block, in which
exceptions are handled. The advantage of using catch block is all possible
exceptions will be caught. If no catch handler matches the type of a thrown
object, its continue search in next try block if there is, if not terminate.
try
{
DangerousStatement
throw exception();
}
catch(<exception_class> <object>)
{
//perform error processing
}
B TRY, THROW AND CATCH (CONT.)
4. The statement throw use to process exception by catch
handler associated with the try .
try
{
DangerousStatement
throw exception();
}
catch(<exception_class> <object>)
{
//perform error processing
}
C STANDARD LIBRARY EXCEPTION
Exception Description
class Number
{
public :
void display( int a)
{int answer;
try{
if(a>100)
throw exception();
answer=100/a;
cout<<"Your number divide by 100 :"<<answer;
cout<<"\n";
}catch(exception &){
cout<<"Exception occured : Enter number <=100."<<endl;
}
}
};
void main()
{
int x;
cout<<"Enter number to divide by 100 :";
cin>>x;
Number n;
n.display(x);
}
D EXAMPLE 2
#include <iostream.h>
#include <stdexcept>
int main()
{
try
{
int age;
cout << "enter age: ";
cin >> age;
if(cin.fail())
throw exception();
cout << "your age "<<age<<endl;
}
catch(exception exc)
{
cout <<"error"<<endl;
}
system("pause");
return(0);
}