Exception
Handling
Dealing with exceptions
What is Exception?
An exception is an unexpected event that occurs during
runtime and causes normal program flow to be disrupted.
Some common examples:
 Divide by zero errors
 Accessing the elements of an array beyond its range
 Invalid input
 Hard disk crash
 Opening a non-existent file
Exception Handling:
The way of handling anomalous situations in a program-run is
known as Exception Handling.
Advantages:
 Exception handling separates error-handling code from
normal code
 It clarifies the code and enhances readability
It makes clear, robust and fault-tolerant programs
Concept of Exception Handling:
Write code such that it raises an error flag every
time something goes wrong
• [throw exception]
Error flag is raised, then
Call the Error-handling routine
• [catch exception]
1
2
3
Syntax:
 In a program a block of code which can produce error is placed
in try block.When an exception is detected in try it is thrown
using throw statement
Try
{
throw expression;
}
catch(type argument)
{
//exception handling code
}
TRY BLOCK
Detects &Throws
exceptions
Exception
object
CATCH BLOCK
Catch & handles
exception
Syntax(continue).
Int num = 5;
string str = "Something is wrong!!!";
Throw expression Effect
throw 4; The constant value 4 is thrown.
throw x; The value of the variable x is thrown.
throw str; The string str is thrown.
throw string("Exception found!"); An anonymous string object with the
string "Exception found!“ thrown.
Syntax(continue).
catch (int x)
This statement can catch only integer catch block parameter.
Catch(. . .) //with ellipses(three dots)
This statement can catch any type of catch block parameter.
If we have more than one catch block then catch block with ellipses appears at last.
Catch block
parameter
Terminate Program:
Example(Divide by Zero Problem):
int main()
{
int dividend, divisor;
try
{
cout<<"Enter dividend: ";cin>>dividend;
cout<<"Enter divisor: ";cin>>divisor;
If(divisor==0)
throw divisor; //or throw 0;
cout<<"Quotient= "<<dividend/divisor<<endl;
}
catch(int x)
{
cout<<"Dividing by "<<x<< " is not possible"<<endl;
}
system("pause");
return 0;
}
Syntax(continue):
Something important about try and catch block:
 If no exception is thrown in a try block, all catch blocks associated
with that try block are ignored and program execution resumes after the
last catch block.
 If an exception is thrown in a try block, the remaining statements in that
try block are ignored.
 When an exception is thrown, If the type of thrown exception matches the
parameter type in one of the catch blocks, the code of that catch block executes,
and the remaining catch blocks after this catch block are ignored.
Class Hierarchy of Exception handling:
Exception
Logical
Runtime
Invalid argument Out of range Length error Bad
allocation
Underflow Overflow
 The Exception class is base class and it contains function
“what()”
 The function what() returns a string with an appropriate error
message
 All derived classes of Exception override function what()
to issue .
Example(Out of range and length problem):
int main()
{
string sentence;
string str1, str2, str3;
try
{
sentence = "Testing string exceptions!";
cout << "Sentence = " << sentence<< endl;
cout << "Sentence length = “
<< static_cast<int>(sentence.length())<< endl;
str1 = sentence.substr(8, 20);
cout << "str1 = " << str1<< endl;
str2 = sentence.substr(28, 10);
cout << "str2 = " << str2<< endl;
str3 = "Exception handling. " + sentence;
cout << "str3 = " << str3<< endl;
}
catch (out_of_range re)
{
cout << "In the out_of_range "
<< "catch block: " << re.what()<< endl;
}
catch (length_error le)
{
cout<< "In the length catch block: " << le.what()<< endl;
}
system("pause");
return 0;
}
Terminate Program:
Example(Range problem in stack)
const int MAX = 3; //stack holds 3 integers
class Stack
{
private:
int st[MAX];
int top; //index of top of stack
public:
class Range //exception class for Stack
{ //note: empty class body
};
Stack() //constructor
{ top = -1; }
void push(int var)
{
If(top >= MAX-1) //if stack full,
throw Range(); //throw exception
st[++top] = var; //put number on stack
}
int pop()
{
if(top < 0) //if stack empty,
throw Range(); //throw exception
return st[top--]; //take number off stack
}
};
int main()
{
Stack s1;
try
{
s1.push(11);
s1.push(22);
s1.push(33);
//s1.push(44); //oops: stack full
cout << "1: " << s1.pop() << endl;
cout << "2: " << s1.pop() << endl;
cout << "3: " << s1.pop() << endl;
cout << "4: " << s1.pop() << endl; //oops: stack empty
}
catch(Stack::Range) //exception handler
{
cout << "Exception: Stack Full or Empty" << endl;
}
cout << "Arrive here after catch (or normal exit)" << endl;
system("pause");
return 0;
}
Fix & Continue:
Example(Input Failure Check)
int main()
{
int number;
bool done = false;
string str = "The input stream is in the fail state.";
do
{
try
{
cout <<"Enter an integer: ";cin >> number;
if (!cin)
throw str;
done = true;
cout << "Number = " << number<< endl;
}
catch (string messageStr)
{
cout << "Error: " << messageStr<< endl;
cout << " Restoring the input stream." << endl;
cin.clear();
cin.ignore(100, 'n');
}
}
while (!done);
Fix & Continue:
Example(Input Failure Check)
int main ()
{
try
{
int* myarray= new int[100000000];
}
catch (bad_alloc& ba)
{
cout<< "bad_alloc caught: " << ba.what() << 'n';
}
system("pause");
return 0;
}
Created By: Waqas Abbasi
3327/fbas/bsse/f16-c

Exception handling

  • 2.
  • 3.
    What is Exception? Anexception is an unexpected event that occurs during runtime and causes normal program flow to be disrupted. Some common examples:  Divide by zero errors  Accessing the elements of an array beyond its range  Invalid input  Hard disk crash  Opening a non-existent file
  • 4.
    Exception Handling: The wayof handling anomalous situations in a program-run is known as Exception Handling. Advantages:  Exception handling separates error-handling code from normal code  It clarifies the code and enhances readability It makes clear, robust and fault-tolerant programs
  • 5.
    Concept of ExceptionHandling: Write code such that it raises an error flag every time something goes wrong • [throw exception] Error flag is raised, then Call the Error-handling routine • [catch exception] 1 2 3
  • 6.
    Syntax:  In aprogram a block of code which can produce error is placed in try block.When an exception is detected in try it is thrown using throw statement Try { throw expression; } catch(type argument) { //exception handling code } TRY BLOCK Detects &Throws exceptions Exception object CATCH BLOCK Catch & handles exception
  • 7.
    Syntax(continue). Int num =5; string str = "Something is wrong!!!"; Throw expression Effect throw 4; The constant value 4 is thrown. throw x; The value of the variable x is thrown. throw str; The string str is thrown. throw string("Exception found!"); An anonymous string object with the string "Exception found!“ thrown.
  • 8.
    Syntax(continue). catch (int x) Thisstatement can catch only integer catch block parameter. Catch(. . .) //with ellipses(three dots) This statement can catch any type of catch block parameter. If we have more than one catch block then catch block with ellipses appears at last. Catch block parameter
  • 9.
    Terminate Program: Example(Divide byZero Problem): int main() { int dividend, divisor; try { cout<<"Enter dividend: ";cin>>dividend; cout<<"Enter divisor: ";cin>>divisor; If(divisor==0) throw divisor; //or throw 0; cout<<"Quotient= "<<dividend/divisor<<endl; } catch(int x) { cout<<"Dividing by "<<x<< " is not possible"<<endl; } system("pause"); return 0; }
  • 10.
    Syntax(continue): Something important abouttry and catch block:  If no exception is thrown in a try block, all catch blocks associated with that try block are ignored and program execution resumes after the last catch block.  If an exception is thrown in a try block, the remaining statements in that try block are ignored.  When an exception is thrown, If the type of thrown exception matches the parameter type in one of the catch blocks, the code of that catch block executes, and the remaining catch blocks after this catch block are ignored.
  • 11.
    Class Hierarchy ofException handling: Exception Logical Runtime Invalid argument Out of range Length error Bad allocation Underflow Overflow  The Exception class is base class and it contains function “what()”  The function what() returns a string with an appropriate error message  All derived classes of Exception override function what() to issue .
  • 12.
    Example(Out of rangeand length problem): int main() { string sentence; string str1, str2, str3; try { sentence = "Testing string exceptions!"; cout << "Sentence = " << sentence<< endl; cout << "Sentence length = “ << static_cast<int>(sentence.length())<< endl; str1 = sentence.substr(8, 20); cout << "str1 = " << str1<< endl; str2 = sentence.substr(28, 10); cout << "str2 = " << str2<< endl; str3 = "Exception handling. " + sentence; cout << "str3 = " << str3<< endl; } catch (out_of_range re) { cout << "In the out_of_range " << "catch block: " << re.what()<< endl; } catch (length_error le) { cout<< "In the length catch block: " << le.what()<< endl; } system("pause"); return 0; }
  • 13.
    Terminate Program: Example(Range problemin stack) const int MAX = 3; //stack holds 3 integers class Stack { private: int st[MAX]; int top; //index of top of stack public: class Range //exception class for Stack { //note: empty class body }; Stack() //constructor { top = -1; } void push(int var) { If(top >= MAX-1) //if stack full, throw Range(); //throw exception st[++top] = var; //put number on stack } int pop() { if(top < 0) //if stack empty, throw Range(); //throw exception return st[top--]; //take number off stack } };
  • 14.
    int main() { Stack s1; try { s1.push(11); s1.push(22); s1.push(33); //s1.push(44);//oops: stack full cout << "1: " << s1.pop() << endl; cout << "2: " << s1.pop() << endl; cout << "3: " << s1.pop() << endl; cout << "4: " << s1.pop() << endl; //oops: stack empty } catch(Stack::Range) //exception handler { cout << "Exception: Stack Full or Empty" << endl; } cout << "Arrive here after catch (or normal exit)" << endl; system("pause"); return 0; }
  • 15.
    Fix & Continue: Example(InputFailure Check) int main() { int number; bool done = false; string str = "The input stream is in the fail state."; do { try { cout <<"Enter an integer: ";cin >> number; if (!cin) throw str; done = true; cout << "Number = " << number<< endl; } catch (string messageStr) { cout << "Error: " << messageStr<< endl; cout << " Restoring the input stream." << endl; cin.clear(); cin.ignore(100, 'n'); } } while (!done);
  • 16.
    Fix & Continue: Example(InputFailure Check) int main () { try { int* myarray= new int[100000000]; } catch (bad_alloc& ba) { cout<< "bad_alloc caught: " << ba.what() << 'n'; } system("pause"); return 0; }
  • 17.
    Created By: WaqasAbbasi 3327/fbas/bsse/f16-c