F3031
Object Oriented Programming
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
1. An Exception is an indication/merujuk of a problem that
occurs during a program’s execution, example.
I. Insufficient memory
II. Division by zero
III. Array subscript out of bound
IV. Invalid function parameter
V. Arithmetic overflow
Exception Handling Concept:
Exception handling enables programmers to create
applications that can resolve (or handle) exceptions
B TRY, THROW AND CATCH
1. An exception is thrown by using the throw keyword
from inside the try block. Exception handlers are
declared with the keyword catch, which must be placed
immediately after the try block:
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 .
5. You will normally find throw statement at:
Inside try block
Inside catch block
When declaring a function
try
{
DangerousStatement
throw exception();
}
catch(<exception_class> <object>)
{
//perform error processing
}
C STANDARD LIBRARY EXCEPTION
Exception Description
bad_alloc thrown by new on allocation failure
bad_cast thrown by dynamic_cast when fails with a
referenced type
bad_exception thrown when an exception type doesn't
match any catch
bad_typeid thrown by typeid
D EXAMPLE 1
#include<iostream.h>
#include<stdexcept>
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;
[Link](x);
}
D EXAMPLE 2
#include <iostream.h>
#include <stdexcept>
int main()
{
try
{
int age;
cout << "enter age: ";
cin >> age;
if([Link]())
throw exception();
cout << "your age "<<age<<endl;
}
catch(exception exc)
{
cout <<"error"<<endl;
}
system("pause");
return(0);
}