0% found this document useful (0 votes)
17 views20 pages

C++ Exception Handling

The document provides an overview of exception handling in C++, detailing the use of keywords 'try', 'throw', and 'catch' to manage errors during program execution. It includes several examples demonstrating how to throw exceptions, catch specific types, and define custom exceptions. Additionally, it explains nested try/catch blocks and the use of a catch-all block to handle any type of exception.

Uploaded by

Saad2222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views20 pages

C++ Exception Handling

The document provides an overview of exception handling in C++, detailing the use of keywords 'try', 'throw', and 'catch' to manage errors during program execution. It includes several examples demonstrating how to throw exceptions, catch specific types, and define custom exceptions. Additionally, it explains nested try/catch blocks and the use of a catch-all block to handle any type of exception.

Uploaded by

Saad2222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Video

Lecture

Object Oriented
Programming
Excepting Handling
Engr. Rashid Farid Chishti
[email protected]
https://youtube.com/rfchishti
https://sites.google.com/site/chishti

International Islamic University H-10, Islamabad, Pakistan


http://www.iiu.edu.pk 1
Introduction
 An exception is a problem that arises during the execution of a program.
 When executing C++ code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, an attempt to divide by zero or
other unforeseeable things.

 Exception handling in C++ consist of three keywords: try, throw and catch:
 try − The try statement allows you to define a block of code to be tested for
errors while it is being executed.
 throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
 catch − The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
Example 1: Exception Handling
#include <iostream> cout << "After catch "
#include <stdlib.h> << "(Will be executed) \n";
using namespace std; system("PAUSE");
int main() { return 0;
int x = -1; // Some code }
cout << "Before try \n";
try {
cout << "Inside try \n";
if (x < 0) {
throw x;
cout << "After throw "
<< "(Never executed) \n";
}
}
catch (int x) {
cout <<"Exception Caught and x =
"
<< x << endl; Page Page
}
Throwing Exceptions
 Exceptions can be thrown anywhere within a code block using throw
statement. The operand of the throw statement determines a type for the
exception and can be any expression and the type of the result of the
expression determines the type of exception thrown.
 Following is an example of throwing an exception when dividing by zero
condition occurs:
double division(int a, int b) {
if (b == 0) {
throw "Division by zero
condition!";
}
return (a / b);
}
Example 2: Divide by Zero Exception
#include <iostream> int main() {
#include <stdlib.h> int x = 50, y = 0;
using namespace std; double z = 0;
double division(int a, int b) { try {
if (b == 0) { z = division(x, y);
throw "Division by zero cout << z << endl;
condition!"; }
} catch (const char* msg) {
return (a / b); cout << msg << endl;
} }
Because we are raising system("PAUSE");
(throwing) an exception of return 0;
type const char*, so while }
catching this exception, we
have to use const char* in
catch block.
Page Page
Catching Exceptions
 The catch block following the try block catches any exception. You can specify
what type of exception you want to catch and this is determined by the
exception declaration that appears in parentheses following the keyword
catch. try {
// protected code
}
catch (ExceptionName e) {
// code to handle ExceptionName
exception
}
 Above code will catch an exception of ExceptionName type. If you want to
specify that a catch block should handle any type of exception that is thrown
in a try block, you must put an ellipsis, ..., between the parentheses enclosing
the exception declaration as follows
Example 3: Exception Handling
#include <iostream> catch (int myNum) {
#include <exception> cout << "Access denied - "
using namespace std; << "You must be at least "
<< "18 years old.\n";
int main() { cout << "Your Age is: " << myNum
try { << endl;
int age = 15; }
if (age >= 18) { system("PAUSE");
cout << "Access granted - " return 0;
<< "you are old enough."; }
}
else {
throw (age);
}
}

Page Page
Example 3 Explained
 We use the try block to test some code: If the age variable is less than 18, we
will throw an exception, and handle it in our catch block.

 In the catch block, we catch the error and do something about it. The catch
statement takes a parameter: in our example we use an int variable (myNum)
(because we are throwing an exception of int type in the try block (age)), to
output the value of age.

 If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater than
18), the catch block is skipped: The catch block following the try block catches
any exception. You can specify what type of exception you want to catch and
this is determined by the exception declaration that appears in parentheses
following the keyword catch.
Example 4: Exception Handling Using Error Number
#include <iostream> catch (int e) {
#include <exception> cout << "Access denied\n";
using namespace std; cout << "Error Number is: "
int main() { << e
try { << endl;
int age = 15; }
if (age >= 18) { system("PAUSE");
cout << "Access granted - return 0;
" } You can also use the throw
<< "you are old keyword to output a reference
enough."; number, like a custom error
} number/code for organizing
else { purposes:
throw (501);
}
}

Page Page
Handle Any Type of Exception
 There is a special catch block called the ‘catch all’ block, written as catch(…),
that can be used to catch all types of exceptions
 If you do not know the throw type used in the try block, you can use the
"three dots" syntax (...) inside the catch block, which will handle any type of
exception
try {
// protected code
throw exception_error
} catch(...) {
// code to handle any exception
}
Example 5: Using Catch All Block
#include <iostream> catch (double e) {
#include <exception> cout << "Age = " << e << endl;
using namespace std; }
catch (...) {
int main() { cout << "Access denied - "
try { << "You must be at least "
int age = 15; << "18 years old.\n";
if (age >= 18) { }
cout << "Access granted - " system("PAUSE");
<< "you are old enough."; return 0;
} }
else {
throw (age);
}
}

Page Page
Handle Any Type of Exception
 If an exception is thrown and not caught anywhere, the program terminates
abnormally.
 For example, in the next program, a char is thrown, but there is no catch block
to catch the char.
Example 6: Ignoing an Exception
#include <iostream>
#include <stdlib.h>
using namespace std;

int main() {
try {
throw 'a';
}
catch (int x) {
cout << "Caught " << x << endl;
}
// catch (char c) {
// cout << "Caught " << c << endl;
// }

system("PAUSE");
return 0;
} Page Page
Example 7: Nested try/catch blocks
#include <iostream> system("PAUSE");
#include <stdlib.h> return 0;
using namespace std; }
int main() { In C++, try/catch blocks can be nested.
try { Also, an exception can be re-thrown
try { using “throw”
throw 20; So a function can handle a part and ask
}
catch (int n) {
the caller to handle the remaining.
cout << "n = "<< n
<< " Handle Partially \n";
throw; // Re-throwing an
exception
}
}
catch (int n) {
cout << "n = "<< n
<< " Handle remaining \n";
Page Page
}
Defining New Exceptions
 You can define your own exceptions by inheriting and overriding exception
class functionality. Following is the example, which shows how you can use
std::exception class to implement your own exception in standard way −

 In the next code, what() is a public method provided by exception class and
it has been overridden by all the child exception classes. This returns the cause
of an exception.
Example 8: Defining New Exceptions
#include <iostream> int main() {
#include <exception> try {
using namespace std; throw MyException();
} catch(MyException& e) {
struct MyException : public std::cout << "MyException
exception { caught"
const char * what () const throw << std::endl;
() { std::cout << e.what()
return "C++ Exception"; << std::endl;
} } catch(std::exception& e) {
}; // Other errors
}
}

Page Page
Example 9: Using Exception Class
#include <iostream> };
using namespace std; int main() {
const int MAX = 3; // stack size Stack s1;
class Stack { try {
private: s1.push(11); s1.push(22);
int st[MAX]; int top; s1.push(33); // s1.push(44);
public: cout << s1.pop() << endl;
class Exception_Full { }; cout << s1.pop() << endl;
class Exception_Empty { }; cout << s1.pop() << endl;
Stack() { top = -1; } cout << s1.pop() << endl;
void push(int var) { }
if (top >= MAX - 1) //if stack catch (Stack::Exception_Full) {
full, cout << "Exception: Stack Full" << endl;
throw Exception_Full(); }
st[++top] = var; catch (Stack::Exception_Empty) {
} cout << "Exception: Stack Empty" <<
int pop() { // take number off stack endl;
if (top < 0) //if stack empty, }
throw Exception_Empty(); cout << "I am outside of try / catch "
return st[top--]; << endl; return 0;
Page Page
} }
Example 10: Exceptions with the Distance Class
#include <iostream> void showdist(){
#include <stdlib.h> cout << feet << "\' - " << inches << "\"\
using namespace std; n";
class Distance { }
private: };
int feet; float inches; int main() {
public: try {
class Inches_Ex { }; //exception class Distance dist1(17, 3.5); //2-arg
Distance() { feet = 0; inches = 0.0; } constructor
Distance(int ft, float in) { Distance dist2; // no-arg constructor
if (in >= 12.0) // if inches too dist2.getdist(); //get distance from
big, user
throw Inches_Ex(); //throw cout << "dist1 = "; dist1.showdist();
exception cout << "dist2 = "; dist2.showdist();
feet = ft; inches = in; }
} catch (Distance::Inches_Ex) {
void getdist() { cout << "Initialization error : "
cout << "Enter feet : "; cin >> << "inches value is too
feet; large."<<endl;
cout << " inches : "; cin >> }
1 Page
inches; system("pause");
Example 11: Exception with arguments
#include <iostream> class Distance {
#include <stdlib.h> private:
#include <string> int feet; float inches;
public:
using namespace std; Distance() { feet = 0; inches = 0.0; }
Distance(int ft, float in) {
class Inches_Ex { // exception class if (in >= 12.0) // if inches too big,
public: throw Inches_Ex("2 - arg constructor",
string origin; // for name of routine in);
float iValue; // for inches value feet = ft; inches = in;
}
Inches_Ex(string str, float in) { void getdist() {
origin = str; // store cout << "Enter feet : "; cin >> feet;
string cout << " inches : "; cin >> inches;
iValue = in; // store if (inches >= 12.0)
inches throw Inches_Ex("in getdist()",
} inches);
}; // end of exception class }
void showdist() {
cout << feet << "\' - " << inches << "\"\
P1 Page
n";
Example 12: Exception with arguments
int main() {
try {
Distance dist1(17, 3.5);
Distance dist2; // no-arg constructor
dist2.getdist();
cout << "dist1 = "; dist1.showdist();
cout << "dist2 = "; dist2.showdist();
}
catch (Inches_Ex e) {
cout << "Initialization error in " << e.origin << endl
<< "Inches value of " << e.iValue << " is too large." << endl;
}
system("pause");
return 0;
}

Page

You might also like