Professional Documents
Culture Documents
Algorithm:
Step1: Get the input for number of times the operation has to be repeated , say n
Step2: Repeat until n less than zero
Step2: Get the input for a, b and c
Step3: Check for b and c unequality
Step4: if b and c are unequal , perform the operation a/(b-c),
Step5: else throw exception saying divide by zero and continue for next iteration
This process involves separate error handling code that performs the
following tasks
Identify the problem (Hit the exception)
try block
Exception object
catch block
catch block
}
catch (int i) {
cout<< “ caught the exception \n “; 23
Catching Mechanism
void main() {
void Xhandler(int test) {cout << "Start\n";
try{ Xhandler(1);
if(test) throw test; Xhandler(2);
else throw "Value is Xhandler(0);
zero";
Xhandler(3);
}
cout << “End"; }
catch(int i) {
cout << "Caught Exception
#: " << i;
Output:
}
Catch All Exceptions
For example:
WIN 2015-16, CSE1002 Problem Solving with Object Oriented Programming
27
void test ( int x) {
try
{ if(x==0) throw x; //int
if(x==-1) throw ‘x’; //char
if(x==1) throw 1.0; //float
}
catch(...) // catch all
{
cout<<” caught an exception”;
}
WIN 2015-16, CSE1002 Problem Solving with Object Oriented Programming
} 28
Exercises
1. Write a C++ code for a simple calculator with exception handling for division
by zero.
2. Write a C++ code to check the password with minimum six characters, at least
1 number and at least one special character.
3. Consider a department store that makes ‘n’ sales in a day. The stores records
the name of the person, item purchased, no. of quantity purchased and price of
single unit. It calculates the total amount for each purchase (quantity * price).
By the end of each day the owner calculates the cumulative total of sales
made, the maximum and minimum amount of sales made. Set any threshold
for minimum sales, throw the exception if it reaches below the threshold.
4. Create a bank account, the account when the withdrawal amount exceeds the
amount of access, an exception is thrown as "out of balance."
5. Write a method void triangle(int a,int b,int c), judge whether three parameters
can form a triangle. Throw an exception if it can't form a triangle as
IllegalArgumentException, display exception information.