SlideShare a Scribd company logo
1
 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.
Introduction
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
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;
}
Example 1: Exception Handling
cout << "After catch "
<< "(Will be executed) n";
system("PAUSE");
return 0;
}
Page 1 Page 2
 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:
Throwing Exceptions
double division(int a, int b) {
if (b == 0) {
throw "Division by zero condition!";
}
return (a / b);
}
#include <iostream>
#include <stdlib.h>
using namespace std;
double division(int a, int b) {
if (b == 0) {
throw "Division by zero condition!";
}
return (a / b);
}
Example 2: Divide by Zero Exception
int main() {
int x = 50, y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}
catch (const char* msg) {
cout << msg << endl;
}
system("PAUSE");
return 0;
}
Page 1 Page 2
Because we are raising
(throwing) an exception of type
const char*, so while catching
this exception, we have to use
const char* in catch block.
 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.
 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
Catching Exceptions
try {
// protected code
}
catch (ExceptionName e) {
// code to handle ExceptionName exception
}
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - "
<< "you are old enough.";
}
else {
throw (age);
}
}
Example 3: Exception Handling
catch (int myNum) {
cout << "Access denied - "
<< "You must be at least "
<< "18 years old.n";
cout << "Your Age is: " << myNum
<< endl;
}
system("PAUSE");
return 0;
}
Page 1 Page 2
 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 3 Explained
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - "
<< "you are old enough.";
}
else {
throw (501);
}
}
Example 4: Exception Handling Using Error Number
catch (int e) {
cout << "Access deniedn";
cout << "Error Number is: " << e
<< endl;
}
system("PAUSE");
return 0;
}
Page 1 Page 2
You can also use the throw keyword to
output a reference number, like a
custom error number/code for
organizing purposes:
 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
Handle Any Type of Exception
try {
// protected code
throw exception_error
} catch(...) {
// code to handle any exception
}
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - "
<< "you are old enough.";
}
else {
throw (age);
}
}
Example 5: Using Catch All Block
catch (double e) {
cout << "Age = " << e << endl;
}
catch (...) {
cout << "Access denied - "
<< "You must be at least "
<< "18 years old.n";
}
system("PAUSE");
return 0;
}
Page 1 Page 2
 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.
Handle Any Type of 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;
}
Example 6: Ignoing an Exception
Page 1 Page 2
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
try {
try {
throw 20;
}
catch (int n) {
cout << "n = "<< n
<< " Handle Partially n";
throw; // Re-throwing an exception
}
}
catch (int n) {
cout << "n = "<< n
<< " Handle remaining n";
}
Example 7: Nested try/catch blocks
system("PAUSE");
return 0;
}
Page 1 Page 2
In C++, try/catch blocks can be nested.
Also, an exception can be re-thrown
using “throw”
So a function can handle a part and ask
the caller to handle the remaining.
 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.
Defining New Exceptions
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception {
const char * what () const throw () {
return "C++ Exception";
}
};
Example 8: Defining New Exceptions
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught"
<< std::endl;
std::cout << e.what()
<< std::endl;
} catch(std::exception& e) {
// Other errors
}
}
Page 1 Page 2
#include <iostream>
using namespace std;
const int MAX = 3; // stack size
class Stack {
private:
int st[MAX]; int top;
public:
class Exception_Full { };
class Exception_Empty { };
Stack() { top = -1; }
void push(int var) {
if (top >= MAX - 1) //if stack full,
throw Exception_Full();
st[++top] = var;
}
int pop() { // take number off stack
if (top < 0) //if stack empty,
throw Exception_Empty();
return st[top--];
}
Example 9: Using Exception Class
};
int main() {
Stack s1;
try {
s1.push(11); s1.push(22);
s1.push(33); // s1.push(44);
cout << s1.pop() << endl;
cout << s1.pop() << endl;
cout << s1.pop() << endl;
cout << s1.pop() << endl;
}
catch (Stack::Exception_Full) {
cout << "Exception: Stack Full" << endl;
}
catch (Stack::Exception_Empty) {
cout << "Exception: Stack Empty" << endl;
}
cout << "I am outside of try / catch "
<< endl; return 0;
}
Page 1 Page 2
#include <iostream>
#include <stdlib.h>
using namespace std;
class Distance {
private:
int feet; float inches;
public:
class Inches_Ex { }; //exception class
Distance() { feet = 0; inches = 0.0; }
Distance(int ft, float in) {
if (in >= 12.0) // if inches too big,
throw Inches_Ex(); //throw exception
feet = ft; inches = in;
}
void getdist() {
cout << "Enter feet : "; cin >> feet;
cout << " inches : "; cin >> inches;
if (inches >= 12.0)
throw Inches_Ex(); //throw exception
}
Example 10: Exceptions with the Distance Class
void showdist(){
cout << feet << "' - " << inches << ""n";
}
};
int main() {
try {
Distance dist1(17, 3.5); //2-arg constructor
Distance dist2; // no-arg constructor
dist2.getdist(); //get distance from user
cout << "dist1 = "; dist1.showdist();
cout << "dist2 = "; dist2.showdist();
}
catch (Distance::Inches_Ex) {
cout << "Initialization error : "
<< "inches value is too large."<<endl;
}
system("pause");
return 0;
}
1 Page 2
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class Inches_Ex { // exception class
public:
string origin; // for name of routine
float iValue; // for inches value
Inches_Ex(string str, float in) {
origin = str; // store string
iValue = in; // store inches
}
}; // end of exception class
Example 11: Exception with arguments
class Distance {
private:
int feet; float inches;
public:
Distance() { feet = 0; inches = 0.0; }
Distance(int ft, float in) {
if (in >= 12.0) // if inches too big,
throw Inches_Ex("2 - arg constructor", in);
feet = ft; inches = in;
}
void getdist() {
cout << "Enter feet : "; cin >> feet;
cout << " inches : "; cin >> inches;
if (inches >= 12.0)
throw Inches_Ex("in getdist()", inches);
}
void showdist() {
cout << feet << "' - " << inches << ""n";
}
};
P1 Page 2
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;
}
Example 12: Exception with arguments
Page 3

More Related Content

Similar to Object Oriented Programming Using C++: C++ Exception Handling.pptx

Exception handling
Exception handlingException handling
Exception handling
Prafull Johri
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++
IRJET Journal
 
Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Prasad Sawant
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
Rajan Shah
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Java unit3
Java unit3Java unit3
Java unit3
Abhishek Khune
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
sivakumarmcs
 
Exceptions in c++
Exceptions in c++Exceptions in c++
Exceptions in c++
Kuntal Bhowmick
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
Ravindra Rathore
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Exception handling
Exception handlingException handling
Exception handling
zindadili
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
Sunil OS
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13
Niit Care
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
People Strategists
 
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptxWINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
ssusercd11c4
 

Similar to Object Oriented Programming Using C++: C++ Exception Handling.pptx (20)

Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Exception handling
Exception handlingException handling
Exception handling
 
Java unit3
Java unit3Java unit3
Java unit3
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
 
Exceptions in c++
Exceptions in c++Exceptions in c++
Exceptions in c++
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
 
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptxWINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
 

More from RashidFaridChishti

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
RashidFaridChishti
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
RashidFaridChishti
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 

More from RashidFaridChishti (20)

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 

Recently uploaded

Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
Indrajeet sahu
 
Introduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.pptIntroduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.ppt
Dwarkadas J Sanghvi College of Engineering
 
AI-Based Home Security System : Home security
AI-Based Home Security System : Home securityAI-Based Home Security System : Home security
AI-Based Home Security System : Home security
AIRCC Publishing Corporation
 
OOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming languageOOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming language
PreethaV16
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
nedcocy
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
sydezfe
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
Atif Razi
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
ijseajournal
 
smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...
um7474492
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
2. protection of river banks and bed erosion protection works.ppt
2. protection of river banks and bed erosion protection works.ppt2. protection of river banks and bed erosion protection works.ppt
2. protection of river banks and bed erosion protection works.ppt
abdatawakjira
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 

Recently uploaded (20)

Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
 
Introduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.pptIntroduction to Computer Networks & OSI MODEL.ppt
Introduction to Computer Networks & OSI MODEL.ppt
 
AI-Based Home Security System : Home security
AI-Based Home Security System : Home securityAI-Based Home Security System : Home security
AI-Based Home Security System : Home security
 
OOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming languageOOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming language
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
 
smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...smart pill dispenser is designed to improve medication adherence and safety f...
smart pill dispenser is designed to improve medication adherence and safety f...
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
2. protection of river banks and bed erosion protection works.ppt
2. protection of river banks and bed erosion protection works.ppt2. protection of river banks and bed erosion protection works.ppt
2. protection of river banks and bed erosion protection works.ppt
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 

Object Oriented Programming Using C++: C++ Exception Handling.pptx

  • 1. 1
  • 2.  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. Introduction
  • 3. #include <iostream> #include <stdlib.h> using namespace std; int main() { 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; } Example 1: Exception Handling cout << "After catch " << "(Will be executed) n"; system("PAUSE"); return 0; } Page 1 Page 2
  • 4.  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: Throwing Exceptions double division(int a, int b) { if (b == 0) { throw "Division by zero condition!"; } return (a / b); }
  • 5. #include <iostream> #include <stdlib.h> using namespace std; double division(int a, int b) { if (b == 0) { throw "Division by zero condition!"; } return (a / b); } Example 2: Divide by Zero Exception int main() { int x = 50, y = 0; double z = 0; try { z = division(x, y); cout << z << endl; } catch (const char* msg) { cout << msg << endl; } system("PAUSE"); return 0; } Page 1 Page 2 Because we are raising (throwing) an exception of type const char*, so while catching this exception, we have to use const char* in catch block.
  • 6.  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.  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 Catching Exceptions try { // protected code } catch (ExceptionName e) { // code to handle ExceptionName exception }
  • 7. #include <iostream> #include <exception> using namespace std; int main() { try { int age = 15; if (age >= 18) { cout << "Access granted - " << "you are old enough."; } else { throw (age); } } Example 3: Exception Handling catch (int myNum) { cout << "Access denied - " << "You must be at least " << "18 years old.n"; cout << "Your Age is: " << myNum << endl; } system("PAUSE"); return 0; } Page 1 Page 2
  • 8.  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 3 Explained
  • 9. #include <iostream> #include <exception> using namespace std; int main() { try { int age = 15; if (age >= 18) { cout << "Access granted - " << "you are old enough."; } else { throw (501); } } Example 4: Exception Handling Using Error Number catch (int e) { cout << "Access deniedn"; cout << "Error Number is: " << e << endl; } system("PAUSE"); return 0; } Page 1 Page 2 You can also use the throw keyword to output a reference number, like a custom error number/code for organizing purposes:
  • 10.  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 Handle Any Type of Exception try { // protected code throw exception_error } catch(...) { // code to handle any exception }
  • 11. #include <iostream> #include <exception> using namespace std; int main() { try { int age = 15; if (age >= 18) { cout << "Access granted - " << "you are old enough."; } else { throw (age); } } Example 5: Using Catch All Block catch (double e) { cout << "Age = " << e << endl; } catch (...) { cout << "Access denied - " << "You must be at least " << "18 years old.n"; } system("PAUSE"); return 0; } Page 1 Page 2
  • 12.  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. Handle Any Type of Exception
  • 13. #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; } Example 6: Ignoing an Exception Page 1 Page 2
  • 14. #include <iostream> #include <stdlib.h> using namespace std; int main() { try { try { throw 20; } catch (int n) { cout << "n = "<< n << " Handle Partially n"; throw; // Re-throwing an exception } } catch (int n) { cout << "n = "<< n << " Handle remaining n"; } Example 7: Nested try/catch blocks system("PAUSE"); return 0; } Page 1 Page 2 In C++, try/catch blocks can be nested. Also, an exception can be re-thrown using “throw” So a function can handle a part and ask the caller to handle the remaining.
  • 15.  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. Defining New Exceptions
  • 16. #include <iostream> #include <exception> using namespace std; struct MyException : public exception { const char * what () const throw () { return "C++ Exception"; } }; Example 8: Defining New Exceptions int main() { try { throw MyException(); } catch(MyException& e) { std::cout << "MyException caught" << std::endl; std::cout << e.what() << std::endl; } catch(std::exception& e) { // Other errors } } Page 1 Page 2
  • 17. #include <iostream> using namespace std; const int MAX = 3; // stack size class Stack { private: int st[MAX]; int top; public: class Exception_Full { }; class Exception_Empty { }; Stack() { top = -1; } void push(int var) { if (top >= MAX - 1) //if stack full, throw Exception_Full(); st[++top] = var; } int pop() { // take number off stack if (top < 0) //if stack empty, throw Exception_Empty(); return st[top--]; } Example 9: Using Exception Class }; int main() { Stack s1; try { s1.push(11); s1.push(22); s1.push(33); // s1.push(44); cout << s1.pop() << endl; cout << s1.pop() << endl; cout << s1.pop() << endl; cout << s1.pop() << endl; } catch (Stack::Exception_Full) { cout << "Exception: Stack Full" << endl; } catch (Stack::Exception_Empty) { cout << "Exception: Stack Empty" << endl; } cout << "I am outside of try / catch " << endl; return 0; } Page 1 Page 2
  • 18. #include <iostream> #include <stdlib.h> using namespace std; class Distance { private: int feet; float inches; public: class Inches_Ex { }; //exception class Distance() { feet = 0; inches = 0.0; } Distance(int ft, float in) { if (in >= 12.0) // if inches too big, throw Inches_Ex(); //throw exception feet = ft; inches = in; } void getdist() { cout << "Enter feet : "; cin >> feet; cout << " inches : "; cin >> inches; if (inches >= 12.0) throw Inches_Ex(); //throw exception } Example 10: Exceptions with the Distance Class void showdist(){ cout << feet << "' - " << inches << ""n"; } }; int main() { try { Distance dist1(17, 3.5); //2-arg constructor Distance dist2; // no-arg constructor dist2.getdist(); //get distance from user cout << "dist1 = "; dist1.showdist(); cout << "dist2 = "; dist2.showdist(); } catch (Distance::Inches_Ex) { cout << "Initialization error : " << "inches value is too large."<<endl; } system("pause"); return 0; } 1 Page 2
  • 19. #include <iostream> #include <stdlib.h> #include <string> using namespace std; class Inches_Ex { // exception class public: string origin; // for name of routine float iValue; // for inches value Inches_Ex(string str, float in) { origin = str; // store string iValue = in; // store inches } }; // end of exception class Example 11: Exception with arguments class Distance { private: int feet; float inches; public: Distance() { feet = 0; inches = 0.0; } Distance(int ft, float in) { if (in >= 12.0) // if inches too big, throw Inches_Ex("2 - arg constructor", in); feet = ft; inches = in; } void getdist() { cout << "Enter feet : "; cin >> feet; cout << " inches : "; cin >> inches; if (inches >= 12.0) throw Inches_Ex("in getdist()", inches); } void showdist() { cout << feet << "' - " << inches << ""n"; } }; P1 Page 2
  • 20. 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; } Example 12: Exception with arguments Page 3