SlideShare a Scribd company logo
OOPS THROUGH C++
Dr. Chandra Sekhar Sanaboina
Assistant Professor
Department of Computer Science and Engineering
University College of Engineering Kakinada
Jawaharlal Nehru Technological University Kakinada
Website: https://drcs.info
1
Youtube Link:
https://www.youtube.com/watch?v=nPjHraTbPeY&list=PLT1ngltOnlJiHbzVvjkU8VzQt9oam8ji4
UNIT – V
TEMPLATES
EXCEPTION HANDLING
2
AGENDA
• Templates –
• Generic Programming with Templates
• Need for Templates
• Definition of class Templates
• Normal Function Templates
• Over Loading of Template Function
• Bubble Sort Using Function Templates
• Difference Between Templates and Macros
• Linked Lists with Templates
• Exception Handling
• Principles of Exception Handling
• The Keywords try throw and catch
• Multiple Catch Statements
• Specifying Exceptions
3
GENERIC PROGRAMMING
WITH TEMPLATES
4
FUNCTION OVERLOADING
5
OVERLOADING FUNCTION
• Function Overloading:
• the function may have the same definition, but with different
arguments
6
FUNCTION OVERLOADING – 1
// overloading functions
#include <iostream>
using namespace std;
int operate (int a, int b)
{
return (a*b);
}
double operate (double a, double
b)
{
return (a/b);
}
int main ()
{
int x=5,y=2;
double n=5.0,m=2.0;
cout << operate (x,y) << 'n';
cout << operate (n,m) << 'n';
return 0;
}
Note: Both functions have quite
different behaviors, the int version
multiplies its arguments, while
the double version divides them.
This is generally not a good idea. Two
functions with the same name are
generally expected to have -at least-
a similar behavior
7
FUNCTION OVERLOADING – 2
// overloaded functions
#include <iostream>
using namespace std;
int sum (int a, int b)
{
return a+b;
}
double sum (double a, double b)
{
return a+b;
}
int main ()
{
cout << sum (10,20) << 'n';
cout << sum (1.0,1.5) << 'n';
return 0;
}
Note: sum is overloaded with different
parameter types, but with the exact same
body
Note: The function sum could be overloaded
for a lot of types, and it could make sense
for all of them to have the same body
8
WHY TEMPLATES?
• For cases such as this, C++ has the ability to define
functions with generic types, known as function templates
9
EXAMPLE ON FUNCTION OVERLOADING
#include <bits/stdc++.h>
using namespace std;
// Function to calculate square
void square(int a)
{
cout << "Square of " << a
<< " is " << a * a
<< endl;
}
// Function to calculate square
void square(double a)
{
cout << "Square of " << a
<< " is " << a * a
<< endl;
}
int main()
{
// Function Call for side as
// 9 i.e., integer
square(9);
// Function Call for side as
// 2.25 i.e., double
square(2.25);
return 0;
}
10
GENERIC PROGRAMMING INTRODUCTION
• The method of Generic Programming is implemented to increase the efficiency of
the code
• Generic Programming enables the programmer to write a general algorithm which
will work with all data types
• It eliminates the need to create different algorithms if the data type is an integer,
string or a character
• Simply we can call it as Generics
11
ADVANTAGES OF GENERIC PROGRAMMING
• Code Reusability
• Avoid Function Overloading
• Once written it can be used for multiple times and
cases.
12
ADVANTAGES OF GENERIC PROGRAMMING
• Generics can be implemented in C++ using Templates
• Template is a simple and yet very powerful tool in C++
• The simple idea is to pass data type as a parameter so that we
don’t need to write the same code for different data types
• Example:
• A user need sort() for different data types
• Rather than writing and maintaining the multiple codes, we can write
one sort() and pass data type as a parameter
13
PROGRAMMING EXAMPLE ON GENERICS
#include <iostream>
using namespace std;
template <typename T>
T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
// Call myMax for int
cout << myMax<int>(3, 7) <<
endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0)
<< endl;
// call myMax for char
cout << myMax<char>('g', 'e') <<
endl;
return 0;
} 14
TYPES OF TEMPLATES
15
TYPES OF TEMPLATES
• The concept of templates can be used in two different ways:
• Function Templates
• Class Templates
16
FUNCTION TEMPLATES
17
FUNCTION TEMPLATE
• A function template works in a similar to a normal function, with
one key difference
• A single function template can work with different data types at once
but, a single normal function can only work with one set of data types
• Normally, if you need to perform identical operations on two or
more types of data, you use function overloading to create two
functions with the required function declaration
• However, a better approach would be to use function templates
because you can perform the same task writing less and
maintainable code
18
DECLARE FUNCTION TEMPLATE
• Function template starts with the keyword template followed by template parameters
inside <>
• It is followed by the function declaration
• Syntax:
template <class T>
T someFunction(T arg)
{
... .. ...
}
• In the above code, T is a template argument that accepts different data types (int, float), and class
is a keyword
• You can also use keyword typename instead of class in the above example
19
FUNCTION TEMPLATE EXAMPLE
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1 = 1, i2 = 2;
float f1 = 1.1, f2 = 2.2;
char c1 = 'a', c2 = 'b';
cout << "Before passing data to function template.n";
cout << "i1 = " << i1 << "ni2 = " << i2;
cout << "nf1 = " << f1 << "nf2 = " << f2;
cout << "nc1 = " << c1 << "nc2 = " << c2;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
cout << "nnAfter passing data to function template.n";
cout << "i1 = " << i1 << "ni2 = " << i2;
cout << "nf1 = " << f1 << "nf2 = " << f2;
cout << "nc1 = " << c1 << "nc2 = " << c2;
return 0;
} 20
CLASS TEMPLATE
21
CLASS TEMPLATE
• Like function templates, we can also create class templates for generic class
operations
• Sometimes, we need a class implementation that is same for all classes, only the
data types used are different
• Normally, we would need to create a different class for each data type OR create
different member variables and functions within a single class
• This will unnecessarily expand our code and will be hard to maintain, as a change
is one class/function should be performed on all classes/functions
• However, class templates make it easy to reuse the same code for all data types
22
CLASS TEMPLATE DECLARATION
• Syntax:
template <class T>
class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};
• T is the template argument which is a placeholder for the data type used
• Inside the class body, a member variable var and a member function someOperation() are both of
type T
23
CREATE OBJECTS FOR CLASS TEMPLATES
• Syntax:
• className<dataType> classObject;
• To create a class template object, we need to define the datatype inside a <> at its
creation
• Examples:
• className<int> classObject;
• className<float> classObject;
• className<string> classObject;
24
CLASS TEMPLATE EXAMPLE
#include <iostream>
using namespace std;
template <class T>
class Calculator
{
private:
T num1, num2;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << "
and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() <<
endl;
cout << "Product is: " << multiply() <<
endl;
cout << "Division is: " << divide() << endl;
}
T add() { return num1 + num2; }
T subtract() { return num1 - num2; }
T multiply() { return num1 * num2; }
T divide() { return num1 / num2; }
};
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
cout << "Int results:" << endl;
intCalc.displayResult();
cout << endl << "Float results:" << endl;
floatCalc.displayResult();
return 0;
}
25
OVERLOADING OF TEMPLATE FUNCTION
26
OVERLOADING TEMPLATE FUNCTION
• The name of the function templates are the same but called with
different arguments is known as function template overloading
• A template function can be overloaded either by
• non-template function
• using an ordinary function template
• Using Non-Template Function:
• When a function template is overloaded with a non-template function, the
function name remains the same but the function’s arguments are unlike
• Using Ordinary Function Template:
• If the function template is with the ordinary template, the name of the
function remains the same but the number of parameters differs
27
OVERLOADED TEMPLATE FUNCTION
(USING EXTERNAL FUNCTION)
#include <bits/stdc++.h>
using namespace std;
// Template declaration
template <class T>
// Template overloading of function
void display(T t1)
{
cout << "Displaying Template: "
<< t1 << "n";
}
// Template overloading of function
void display(int t1)
{
cout << "Explicitly display: "
<< t1 << "n";
}
int main()
{
// Function Call with a
// different arguments
display(200);
display(12.40);
display('G');
return 0;
}
28
OVERLOADED TEMPLATE FUNCTION
(USING TEMPLATE FUNCTION)
#include <bits/stdc++.h>
using namespace std;
template <typename T1>
void display(T1 t1)
{
cout << "Displaying Template 1: "<< t1 << "n";
}
template <typename T2>
void display(T2 t1, T2 t2)
{
cout << "Displaying Template 2: "<< t1<< t2 << "n";
}
void display(int t1)
{
cout << "Explicitly display: "<< t1 << "n";
}
int main()
{
display(200);
display(12.40);
display(13.23, 45.46);
display('G');
return 0;
}
29
BUBBLE SORT USING TEMPLATES
30
BUBBLE SORT USING TEMPLATES
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
void BubbleSort(T arr[], int n)
{
for(int i=0;i<n-1;++i){
for(int j=0;j<n-i-1;++j){
if(arr[j]>arr[j+1]){
T temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
}
template<typename T>
void PrintArray(T arr[], int n)
{
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "nn";
}
int main()
{
int arr[] = { 1, 10, 90, 100, -1, 11, 9,
14, 3, 2, 20, 19 };
int n = sizeof(arr) / sizeof(int);
cout << "Array Before Sorting: " <<
endl;
PrintArray(arr, n);
BubbleSort(arr, n);
cout << "Array After Sorting: " <<
endl;
PrintArray(arr, n);
}
31
TEMPLATES
VS
MACROS
32
TEMPLATE VS MACRO
Template Macro
Only available in C++ Used in C and C++
Used to write small functions and classes Used for replacement of numbers, small
inline functions etc.,
More chances of making mistakes Code is simple and easier to understand
Easy to debug, because it undergoes
compilation process.
Difficult to handle errors as they are
handled by pre-processor
Being a function call, they are less efficient
than macros
More efficient as they are compiled
inline
They are considered to be type safe, as
there is compile time checking
Macros do not have any type checking
and therefore are type unsafe
33
DATA TYPE CHECKING
Macro Template
#define swap(x, y)
int main ()
{
int i = 10;
float j = 12.2;
swap(i, j);
}
Note: swap() does not check the data
type
include <iostream>
template <typename T>
T swap(T &a, T &b)
{
T c;
c = b;
b = a;
a = c;
}
int main ()
{
int i = 10;
float j = 12.2;
swap(i, j);
}
34
COMPILATION
Macro Template
Line:1:#define set_userid(x)
Line:2:current_user = x 
Line:3:next_user = x + 1;
Line:4:int main (int argc, char *argv[]
)
Line:5:{
Line:6: int user = 10;
Line:7: set_userid(user);
Line:7:}
Error at Line 7
Note: Compiler is not giving the error
on line 2 where we have missing ";". It
is giving the error where the macro is
called (i.e., line 7)
#include <iostream>
template <typename T>
T swap(T &a, T &b)
{
T c;
c = b
b = a;
a = c;
}
int main ()
{
int i = 10;
int j = 12;
swap(i, j);
}
Note: Compiler is giving the error on
line 2 of template where we have
missing ";".
35
LINKED LISTS WITH TEMPLATES
36
LINKED LIST WITH TEMPLATES
#include <iostream>
using namespace std;
template <typename T>
struct link //one element of list
{
T data; //data item
link* next; //pointer to next link
};
template <class T>
class linklist //a list of links
{
private:
link<T>* first; //pointer to first link
public:
linklist() //no-argument constructor
{ first = NULL; } //no first link
void additem(T d); //add data item (one link)
void display(); //display all links
};
template <class T>
void linklist<T>::additem(T d) //add data item
{
link<T> *newLink = new link<T>;
newLink->data = d;
//insert at head of link list
newLink->next = first;
first = newLink;
}
template <class T>
void linklist<T>::display() //display all links
{
link<T>* current = first; //set ptr to first link
while( current != NULL ) //quit on last link
{
cout << current->data << endl; //print data
current = current->next; //move to next link
}
}
int main()
{
linklist<int> li; //make linked list
li.additem(25); //add four items to list
li.additem(36);
li.additem(49);
li.display(); //display entire list
linklist<char> lch; //make linked list
lch.additem('a'); //add four items to list
lch.additem('b');
lch.additem('c');
lch.display(); //display entire list
return 0;
}
37
EXCEPTION HANDLING
38
PREREQUISITES FOR EXCEPTION HANDLING
39
ERRORS AND TYPES OF ERRORS
• Error:
• An error is an interruption of code execution due to which
the expected output could not be obtained
• Types of Errors:
• Errors are Classified as
• Compile-Time Errors
• Run-Time Errors
• Note: Run-Time Errors are also called as bugs or
exceptions
40
COMPILE TIME ERRORS VS RUN-TIME ERRORS
Compile-Time Errors Run-Time Errors
Occurs with respect to Syntax and Semantics Occurs during the execution of code at
runtime
Detected by compiler at the time of code
development
Not detected by the compiler but are
identified at the time of code execution
Fixed at the time of code development Fixed after code is executed and error gets
identified
Examples:
Missing ; , Missing braces, Missing
parentheses, Undefined Identifier
Examples:
Divide by Zero, Infinite Loop, Wrong Input by
the user, I/O errors, Undefined Object errors
We cannot run the code successfully till we
correct these errors
Stop the program from getting desired results
Example Code:
main(){
Int x=10;
cout<<x
}
Output: error at line 3:8: ; missing
Example Code:
main(){
int a=10;
int b=0;
cout<<a/b;
}
Output: Floating Point Exception
41
INTRODUCTION TO EXCEPTION HANDLING
42
EXCEPTION INTRODUCTION
• An exception is a problem that arises during the execution of a program
• Exceptions are run-time anomalies or abnormal conditions that a program
encounters during its execution
• A C++ exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero
• Exceptions provide a way to transfer control from one part of a program to another
43
EXCEPTION INTRODUCTION CONTD…
• C++ exception handling is built upon three keywords: try, catch, and throw
• try −
• A try block identifies a block of code for which particular exceptions will be activated
• It's followed by one or more catch blocks
• throw −
• Used to throw an exception
• Also used to list the exceptions that a function throws, but doesn’t handle itself
• This is done using a throw keyword
• catch −
• represents a block of code that is executed when a particular exception is thrown
• The catch keyword indicates the catching of an exception
44
EXCEPTION INTRODUCTION CONTD…
• Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords
• A try/catch block is placed around the code that might generate an exception
• Code within a try/catch block is referred to as protected code
45
EXCEPTION INTRODUCTION CONTD…
• Syntax:
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
46
TYPES OF EXCEPTIONS
• There are two types of exceptions:
• Synchronous –
• Exception handling mechanism can handle only Synchronous Errors
• These exceptions are handled by try/catch
• They have a termination model – once the control is thrown from the try
block the control never returns back
• Asynchronous
• Cannot be handled by exception handling mechanisms in C++
• Hardware failures can be treated under this category
• Example:
• program’s control, Disc failure, keyboard interrupts etc.,
47
WHY EXCEPTION HANDLING?
• Separation of Error Handling code from Normal Code
• Functions/Methods can handle any exceptions they choose
• Grouping of Error Types
48
EXCEPTION HANDLING EXAMPLE
#include <iostream>
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 n";
}
cout << "After catch (Will be executed) n";
return 0;
}
49
IMPORTANT POINTS REGARDING
EXCEPTION HANDLING
• There is a special catch block to catch all exceptions
• Implicit type conversion doesn’t happen for primitive types
• If an exception is thrown and not caught anywhere, the program terminates
abnormally
• A derived class exception should be caught before a base class exception
• C++ library has a standard exception class which is base class for all standard
exceptions
• In C++, all exceptions are unchecked…Compiler doesn’t check whether an
exception is caught or not
• Can use functions to specify all uncaught exceptions
• In C++, try-catch blocks can be nested
• When an exception is thrown, all objects created inside the enclosing try block are
destructed before the control is transferred to catch block
50
SPECIAL CATCH BLOCK EXAMPLE
#include <iostream>
using namespace std;
int main()
{
try {
throw 10;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exceptionn";
}
return 0;
}
51
IMPLICIT TYPE CONVERSION DOESN’T
HAPPEN FOR PRIMITIVE TYPES
#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught " << x;
}
catch (...) {
cout << "Default Exceptionn";
}
return 0;
}
52
IF AN EXCEPTION IS THROWN AND NOT
CAUGHT ANYWHERE, THE PROGRAM
TERMINATES ABNORMALLY
#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught ";
}
return 0;
}
53
A DERIVED CLASS EXCEPTION SHOULD BE
CAUGHT BEFORE A BASE CLASS EXCEPTION
#include<iostream>
using namespace std;
class Base {};
class Derived: public Base {};
int main()
{
Derived d;
// some other stuff
try {
// Some monitored code
throw d;
}
catch(Base b) {
cout<<"Caught Base Exception";
}
catch(Derived d) { //This catch block is NEVER executed
cout<<"Caught Derived Exception";
}
getchar();
return 0;
}
Note 1:
If both base and
derived classes are
caught as exceptions
then catch block of
derived class must
appear before the
base class
Note 2:
If we put base class
first then the derived
class catch block will
never be reached 54
FUNCTION TO SPECIFY THE UNCAUGHT
EXCEPTIONS
#include <iostream>
using namespace std;
void fun(int *ptr, int x)
{
if (ptr == NULL)
throw ptr;
if (x == 0)
throw x;
/* Some functionality */
}
int main()
{
try {
fun(NULL, 0);
}
catch(...) {
cout << "Caught exception from fun()";
}
return 0;
}
55
NESTED TRY-CATCH BLOCKS
#include <iostream>
using namespace std;
int main()
{
try {
try {
throw 20;
}
catch (int n) {
cout << "Handle Partially ";
throw; // Re-throwing an exception
}
}
catch (int n) {
cout << "Handle remaining ";
}
return 0;
}
56
ALL OBJECTS CREATED INSIDE THE ENCLOSING
TRY BLOCK ARE DESTRUCTED BEFORE THE
CONTROL IS TRANSFERRED TO CATCH BLOCK
include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "Constructor of Test " << endl; }
~Test() { cout << "Destructor of Test " << endl; }
};
int main()
{
try {
Test t1;
throw 10;
}
catch (int i) {
cout << "Caught " << i << endl;
}
}
57
PRINCIPLES OF EXCEPTION HANDLING
58
PRINCIPLES OF EXCEPTION HANDLING
• If you can't handle an exception, don't catch it
• Catch an exception as close as possible to its source
• If you catch an exception, don't swallow it
• Log an exception where you catch it, unless you plan to re-throw it
• Use as many typed exceptions as you need, particularly for application
exceptions
• By fine graining the throws clause, it is self-documenting and becomes evident to
the caller that different exceptions have to be handled.
• Never throw unchecked exceptions in your methods just because it clutters
the method signature
• Throw Application Exceptions as checked Exceptions and Unrecoverable
System exceptions as unchecked exceptions
• Structure your methods according to how fine-grained your exception
handling must be
59
CHECKED EXCEPTION
VS
UNCHECKED EXCEPTION
60
CHECKED VS UNCHECKED
• Checked Exceptions –
• Checked Exceptions are those that extend java.lang.Exception.
• If your method throws checked exceptions, then the caller is
forced to catch these exceptions at compile time or declare in
the throws clause of the method
• Unchecked Exceptions –
• Unchecked exceptions are those that
extend java.lang.RuntimeException, generally referred to as
runtime exceptions
• If your method throws a runtime exception, the caller of the
method is not forced to catch the exception or add it to the
method signature at compile time
61
SPECIFYING EXCEPTIONS
62
SPECIFYING EXCEPTIONS
• In C++, one can specify the exceptions through
functions
• The programmer can specify which type of exception
he/she wants to throw
63
#include<iostream>
using namespace std;
void test(int x) throw (int,
double)
{
if(x==0)
throw 10;
else if(x==-1)
throw 15.34;
}
int main()
{
try{
test(0);
test(-1);
}
catch(int a)
{
cout<< "Integer caught "<<a;
}
catch(double d)
{
cout<< "double caught"<<d;
}
}
EXAMPLE - 1 ON SPECIFYING EXCEPTIONS
64
EXAMPLE - 2 ON SPECIFYING EXCEPTIONS
#include<iostream>
using namespace std;
void test() throw (int, double,
char, runtime_error)
{
throw runtime_error("What is
happening here??!!");
}
Output: Runtime error caught
What is happening here??!!
int main()
{
try{
test();
}
catch(int a)
{
cout<< "Integer caught "<<a;
}
catch(double d)
{
cout<< "double caught "<<d;
}
catch(char ch)
{
cout<< "Character caught "<<ch;
}
catch(runtime_error r)
{
cout<< "Runtime error caught "<<r.what();
}
}
65
EXAMPLE - 3 ON SPECIFYING EXCEPTIONS
#include<iostream>
using namespace std;
void test() throw ()
{
throw 10;
}
Output: terminate called after
throwing an instance of 'int'
int main()
{
try{
test();
}
catch(int a)
{
cout<< "Integer caught "<<a;
}
catch(double d)
{
cout<< "double caught "<<d;
}
catch(char ch)
{
cout<< "Character caught "<<ch;
}
catch(runtime_error r)
{
cout<< "Runtime error caught
"<<r.what();
}
}
66
EXAMPLE - 4 ON SPECIFYING EXCEPTIONS
#include<iostream>
using namespace std;
void test()
{
throw 10;
}
NOTE: Not specifying any
exceptions
Output: Integer caught 10
int main()
{
try{
test();
}
catch(int a)
{
cout<< "Integer caught "<<a;
}
catch(double d)
{
cout<< "double caught "<<d;
}
catch(char ch)
{
cout<< "Character caught "<<ch;
}
catch(runtime_error r)
{
cout<< "Runtime error caught "<<r.what();
}
}
67
THE END
68

More Related Content

What's hot (20)

PPTX
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
Vraj Patel
 
PPTX
Relational Data Model Introduction
Nishant Munjal
 
PPTX
Database Design
learnt
 
PPTX
Tcp/ip server sockets
rajshreemuthiah
 
PDF
Relational algebra in dbms
Vignesh Saravanan
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PPT
Operator overloading in C++
BalajiGovindan5
 
PPT
ER-Model-ER Diagram
Saranya Natarajan
 
PPSX
Functional dependency
Dashani Rajapaksha
 
PPTX
Nested queries in database
Satya P. Joshi
 
PPTX
Aggregate function
Rayhan Chowdhury
 
PPT
Arrays searching-sorting
Ajharul Abedeen
 
PPTX
Acid properties
Abhilasha Lahigude
 
PPT
Basic concept of OOP's
Prof. Dr. K. Adisesha
 
PDF
Dbms 14: Relational Calculus
Amiya9439793168
 
PPT
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
PPTX
Database : Relational Data Model
Smriti Jain
 
PPT
13. Query Processing in DBMS
koolkampus
 
PPT
Java layoutmanager
Arati Gadgil
 
PPTX
DBMS Keys
Tarun Maheshwari
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
Vraj Patel
 
Relational Data Model Introduction
Nishant Munjal
 
Database Design
learnt
 
Tcp/ip server sockets
rajshreemuthiah
 
Relational algebra in dbms
Vignesh Saravanan
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Operator overloading in C++
BalajiGovindan5
 
ER-Model-ER Diagram
Saranya Natarajan
 
Functional dependency
Dashani Rajapaksha
 
Nested queries in database
Satya P. Joshi
 
Aggregate function
Rayhan Chowdhury
 
Arrays searching-sorting
Ajharul Abedeen
 
Acid properties
Abhilasha Lahigude
 
Basic concept of OOP's
Prof. Dr. K. Adisesha
 
Dbms 14: Relational Calculus
Amiya9439793168
 
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Database : Relational Data Model
Smriti Jain
 
13. Query Processing in DBMS
koolkampus
 
Java layoutmanager
Arati Gadgil
 
DBMS Keys
Tarun Maheshwari
 

Similar to Object Oriented Programming using C++ - Part 5 (20)

PPTX
TEMPLATES IN JAVA
MuskanSony
 
PPTX
Templates presentation
malaybpramanik
 
PPTX
Templates2
zindadili
 
PDF
Templates
Pranali Chaudhari
 
PDF
4.1 C++ Template for engineering course. Learn easily
kk6369150094
 
PPTX
CSE107JAN2023_KMS_Intrnjononolo+CPP.pptx
alaminbuetcse22
 
PPTX
TEMPLATES in C++ are one of important topics in Object Oriented Programming
208BVijaySunder
 
PPTX
Object Oriented Programming using C++: C++ Templates.pptx
RashidFaridChishti
 
PPT
Templates
Nilesh Dalvi
 
PPTX
Function template
Kousalya M
 
PPTX
Polymorphism & Templates
Meghaj Mallick
 
PPTX
Templates1
zindadili
 
PPT
Lecture 04 - Templates.ppt,Class Templates and Function templates
kaurgurkiranpreet92
 
PPT
2CPP15 - Templates
Michael Heron
 
PPTX
4.1 Function Templates,Overlaoding Function Templates.pptx
tirseishwaricomp
 
PPTX
Templates c++ - prashant odhavani - 160920107003
Prashant odhavani
 
PPTX
Templates in c++
ThamizhselviKrishnam
 
PPTX
Templates in c++
Mayank Bhatt
 
PPTX
Lecture 25 - OOPFAST NUCES ISB.ppsx.pptx
UmairHassan488014
 
TEMPLATES IN JAVA
MuskanSony
 
Templates presentation
malaybpramanik
 
Templates2
zindadili
 
4.1 C++ Template for engineering course. Learn easily
kk6369150094
 
CSE107JAN2023_KMS_Intrnjononolo+CPP.pptx
alaminbuetcse22
 
TEMPLATES in C++ are one of important topics in Object Oriented Programming
208BVijaySunder
 
Object Oriented Programming using C++: C++ Templates.pptx
RashidFaridChishti
 
Templates
Nilesh Dalvi
 
Function template
Kousalya M
 
Polymorphism & Templates
Meghaj Mallick
 
Templates1
zindadili
 
Lecture 04 - Templates.ppt,Class Templates and Function templates
kaurgurkiranpreet92
 
2CPP15 - Templates
Michael Heron
 
4.1 Function Templates,Overlaoding Function Templates.pptx
tirseishwaricomp
 
Templates c++ - prashant odhavani - 160920107003
Prashant odhavani
 
Templates in c++
ThamizhselviKrishnam
 
Templates in c++
Mayank Bhatt
 
Lecture 25 - OOPFAST NUCES ISB.ppsx.pptx
UmairHassan488014
 
Ad

More from University College of Engineering Kakinada, JNTUK - Kakinada, India (9)

PDF
Machine Learning - Implementation with Python - 4.pdf
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PDF
Machine Learning - Implementation with Python - 3.pdf
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PDF
Machine Learning - Implementation with Python - 2
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PDF
Machine Learning - Implementation with Python - 1
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PDF
Object Oriented Programming using C++ - Part 1
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PDF
Object Oriented Programming using C++ - Part 2
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PDF
Object Oriented Programming using C++ - Part 4
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PDF
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Machine Learning - Implementation with Python - 4.pdf
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Machine Learning - Implementation with Python - 3.pdf
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Machine Learning - Implementation with Python - 2
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Machine Learning - Implementation with Python - 1
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 1
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 2
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 4
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Ad

Recently uploaded (20)

PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Horarios de distribución de agua en julio
pegazohn1978
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 

Object Oriented Programming using C++ - Part 5

  • 1. OOPS THROUGH C++ Dr. Chandra Sekhar Sanaboina Assistant Professor Department of Computer Science and Engineering University College of Engineering Kakinada Jawaharlal Nehru Technological University Kakinada Website: https://drcs.info 1 Youtube Link: https://www.youtube.com/watch?v=nPjHraTbPeY&list=PLT1ngltOnlJiHbzVvjkU8VzQt9oam8ji4
  • 3. AGENDA • Templates – • Generic Programming with Templates • Need for Templates • Definition of class Templates • Normal Function Templates • Over Loading of Template Function • Bubble Sort Using Function Templates • Difference Between Templates and Macros • Linked Lists with Templates • Exception Handling • Principles of Exception Handling • The Keywords try throw and catch • Multiple Catch Statements • Specifying Exceptions 3
  • 6. OVERLOADING FUNCTION • Function Overloading: • the function may have the same definition, but with different arguments 6
  • 7. FUNCTION OVERLOADING – 1 // overloading functions #include <iostream> using namespace std; int operate (int a, int b) { return (a*b); } double operate (double a, double b) { return (a/b); } int main () { int x=5,y=2; double n=5.0,m=2.0; cout << operate (x,y) << 'n'; cout << operate (n,m) << 'n'; return 0; } Note: Both functions have quite different behaviors, the int version multiplies its arguments, while the double version divides them. This is generally not a good idea. Two functions with the same name are generally expected to have -at least- a similar behavior 7
  • 8. FUNCTION OVERLOADING – 2 // overloaded functions #include <iostream> using namespace std; int sum (int a, int b) { return a+b; } double sum (double a, double b) { return a+b; } int main () { cout << sum (10,20) << 'n'; cout << sum (1.0,1.5) << 'n'; return 0; } Note: sum is overloaded with different parameter types, but with the exact same body Note: The function sum could be overloaded for a lot of types, and it could make sense for all of them to have the same body 8
  • 9. WHY TEMPLATES? • For cases such as this, C++ has the ability to define functions with generic types, known as function templates 9
  • 10. EXAMPLE ON FUNCTION OVERLOADING #include <bits/stdc++.h> using namespace std; // Function to calculate square void square(int a) { cout << "Square of " << a << " is " << a * a << endl; } // Function to calculate square void square(double a) { cout << "Square of " << a << " is " << a * a << endl; } int main() { // Function Call for side as // 9 i.e., integer square(9); // Function Call for side as // 2.25 i.e., double square(2.25); return 0; } 10
  • 11. GENERIC PROGRAMMING INTRODUCTION • The method of Generic Programming is implemented to increase the efficiency of the code • Generic Programming enables the programmer to write a general algorithm which will work with all data types • It eliminates the need to create different algorithms if the data type is an integer, string or a character • Simply we can call it as Generics 11
  • 12. ADVANTAGES OF GENERIC PROGRAMMING • Code Reusability • Avoid Function Overloading • Once written it can be used for multiple times and cases. 12
  • 13. ADVANTAGES OF GENERIC PROGRAMMING • Generics can be implemented in C++ using Templates • Template is a simple and yet very powerful tool in C++ • The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types • Example: • A user need sort() for different data types • Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter 13
  • 14. PROGRAMMING EXAMPLE ON GENERICS #include <iostream> using namespace std; template <typename T> T myMax(T x, T y) { return (x > y) ? x : y; } int main() { // Call myMax for int cout << myMax<int>(3, 7) << endl; // call myMax for double cout << myMax<double>(3.0, 7.0) << endl; // call myMax for char cout << myMax<char>('g', 'e') << endl; return 0; } 14
  • 16. TYPES OF TEMPLATES • The concept of templates can be used in two different ways: • Function Templates • Class Templates 16
  • 18. FUNCTION TEMPLATE • A function template works in a similar to a normal function, with one key difference • A single function template can work with different data types at once but, a single normal function can only work with one set of data types • Normally, if you need to perform identical operations on two or more types of data, you use function overloading to create two functions with the required function declaration • However, a better approach would be to use function templates because you can perform the same task writing less and maintainable code 18
  • 19. DECLARE FUNCTION TEMPLATE • Function template starts with the keyword template followed by template parameters inside <> • It is followed by the function declaration • Syntax: template <class T> T someFunction(T arg) { ... .. ... } • In the above code, T is a template argument that accepts different data types (int, float), and class is a keyword • You can also use keyword typename instead of class in the above example 19
  • 20. FUNCTION TEMPLATE EXAMPLE #include <iostream> using namespace std; template <typename T> void Swap(T &n1, T &n2) { T temp; temp = n1; n1 = n2; n2 = temp; } int main() { int i1 = 1, i2 = 2; float f1 = 1.1, f2 = 2.2; char c1 = 'a', c2 = 'b'; cout << "Before passing data to function template.n"; cout << "i1 = " << i1 << "ni2 = " << i2; cout << "nf1 = " << f1 << "nf2 = " << f2; cout << "nc1 = " << c1 << "nc2 = " << c2; Swap(i1, i2); Swap(f1, f2); Swap(c1, c2); cout << "nnAfter passing data to function template.n"; cout << "i1 = " << i1 << "ni2 = " << i2; cout << "nf1 = " << f1 << "nf2 = " << f2; cout << "nc1 = " << c1 << "nc2 = " << c2; return 0; } 20
  • 22. CLASS TEMPLATE • Like function templates, we can also create class templates for generic class operations • Sometimes, we need a class implementation that is same for all classes, only the data types used are different • Normally, we would need to create a different class for each data type OR create different member variables and functions within a single class • This will unnecessarily expand our code and will be hard to maintain, as a change is one class/function should be performed on all classes/functions • However, class templates make it easy to reuse the same code for all data types 22
  • 23. CLASS TEMPLATE DECLARATION • Syntax: template <class T> class className { ... .. ... public: T var; T someOperation(T arg); ... .. ... }; • T is the template argument which is a placeholder for the data type used • Inside the class body, a member variable var and a member function someOperation() are both of type T 23
  • 24. CREATE OBJECTS FOR CLASS TEMPLATES • Syntax: • className<dataType> classObject; • To create a class template object, we need to define the datatype inside a <> at its creation • Examples: • className<int> classObject; • className<float> classObject; • className<string> classObject; 24
  • 25. CLASS TEMPLATE EXAMPLE #include <iostream> using namespace std; template <class T> class Calculator { private: T num1, num2; public: Calculator(T n1, T n2) { num1 = n1; num2 = n2; } void displayResult() { cout << "Numbers are: " << num1 << " and " << num2 << "." << endl; cout << "Addition is: " << add() << endl; cout << "Subtraction is: " << subtract() << endl; cout << "Product is: " << multiply() << endl; cout << "Division is: " << divide() << endl; } T add() { return num1 + num2; } T subtract() { return num1 - num2; } T multiply() { return num1 * num2; } T divide() { return num1 / num2; } }; int main() { Calculator<int> intCalc(2, 1); Calculator<float> floatCalc(2.4, 1.2); cout << "Int results:" << endl; intCalc.displayResult(); cout << endl << "Float results:" << endl; floatCalc.displayResult(); return 0; } 25
  • 26. OVERLOADING OF TEMPLATE FUNCTION 26
  • 27. OVERLOADING TEMPLATE FUNCTION • The name of the function templates are the same but called with different arguments is known as function template overloading • A template function can be overloaded either by • non-template function • using an ordinary function template • Using Non-Template Function: • When a function template is overloaded with a non-template function, the function name remains the same but the function’s arguments are unlike • Using Ordinary Function Template: • If the function template is with the ordinary template, the name of the function remains the same but the number of parameters differs 27
  • 28. OVERLOADED TEMPLATE FUNCTION (USING EXTERNAL FUNCTION) #include <bits/stdc++.h> using namespace std; // Template declaration template <class T> // Template overloading of function void display(T t1) { cout << "Displaying Template: " << t1 << "n"; } // Template overloading of function void display(int t1) { cout << "Explicitly display: " << t1 << "n"; } int main() { // Function Call with a // different arguments display(200); display(12.40); display('G'); return 0; } 28
  • 29. OVERLOADED TEMPLATE FUNCTION (USING TEMPLATE FUNCTION) #include <bits/stdc++.h> using namespace std; template <typename T1> void display(T1 t1) { cout << "Displaying Template 1: "<< t1 << "n"; } template <typename T2> void display(T2 t1, T2 t2) { cout << "Displaying Template 2: "<< t1<< t2 << "n"; } void display(int t1) { cout << "Explicitly display: "<< t1 << "n"; } int main() { display(200); display(12.40); display(13.23, 45.46); display('G'); return 0; } 29
  • 30. BUBBLE SORT USING TEMPLATES 30
  • 31. BUBBLE SORT USING TEMPLATES #include<iostream> #include<vector> using namespace std; template<typename T> void BubbleSort(T arr[], int n) { for(int i=0;i<n-1;++i){ for(int j=0;j<n-i-1;++j){ if(arr[j]>arr[j+1]){ T temp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = temp; } } } } template<typename T> void PrintArray(T arr[], int n) { for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << "nn"; } int main() { int arr[] = { 1, 10, 90, 100, -1, 11, 9, 14, 3, 2, 20, 19 }; int n = sizeof(arr) / sizeof(int); cout << "Array Before Sorting: " << endl; PrintArray(arr, n); BubbleSort(arr, n); cout << "Array After Sorting: " << endl; PrintArray(arr, n); } 31
  • 33. TEMPLATE VS MACRO Template Macro Only available in C++ Used in C and C++ Used to write small functions and classes Used for replacement of numbers, small inline functions etc., More chances of making mistakes Code is simple and easier to understand Easy to debug, because it undergoes compilation process. Difficult to handle errors as they are handled by pre-processor Being a function call, they are less efficient than macros More efficient as they are compiled inline They are considered to be type safe, as there is compile time checking Macros do not have any type checking and therefore are type unsafe 33
  • 34. DATA TYPE CHECKING Macro Template #define swap(x, y) int main () { int i = 10; float j = 12.2; swap(i, j); } Note: swap() does not check the data type include <iostream> template <typename T> T swap(T &a, T &b) { T c; c = b; b = a; a = c; } int main () { int i = 10; float j = 12.2; swap(i, j); } 34
  • 35. COMPILATION Macro Template Line:1:#define set_userid(x) Line:2:current_user = x Line:3:next_user = x + 1; Line:4:int main (int argc, char *argv[] ) Line:5:{ Line:6: int user = 10; Line:7: set_userid(user); Line:7:} Error at Line 7 Note: Compiler is not giving the error on line 2 where we have missing ";". It is giving the error where the macro is called (i.e., line 7) #include <iostream> template <typename T> T swap(T &a, T &b) { T c; c = b b = a; a = c; } int main () { int i = 10; int j = 12; swap(i, j); } Note: Compiler is giving the error on line 2 of template where we have missing ";". 35
  • 36. LINKED LISTS WITH TEMPLATES 36
  • 37. LINKED LIST WITH TEMPLATES #include <iostream> using namespace std; template <typename T> struct link //one element of list { T data; //data item link* next; //pointer to next link }; template <class T> class linklist //a list of links { private: link<T>* first; //pointer to first link public: linklist() //no-argument constructor { first = NULL; } //no first link void additem(T d); //add data item (one link) void display(); //display all links }; template <class T> void linklist<T>::additem(T d) //add data item { link<T> *newLink = new link<T>; newLink->data = d; //insert at head of link list newLink->next = first; first = newLink; } template <class T> void linklist<T>::display() //display all links { link<T>* current = first; //set ptr to first link while( current != NULL ) //quit on last link { cout << current->data << endl; //print data current = current->next; //move to next link } } int main() { linklist<int> li; //make linked list li.additem(25); //add four items to list li.additem(36); li.additem(49); li.display(); //display entire list linklist<char> lch; //make linked list lch.additem('a'); //add four items to list lch.additem('b'); lch.additem('c'); lch.display(); //display entire list return 0; } 37
  • 40. ERRORS AND TYPES OF ERRORS • Error: • An error is an interruption of code execution due to which the expected output could not be obtained • Types of Errors: • Errors are Classified as • Compile-Time Errors • Run-Time Errors • Note: Run-Time Errors are also called as bugs or exceptions 40
  • 41. COMPILE TIME ERRORS VS RUN-TIME ERRORS Compile-Time Errors Run-Time Errors Occurs with respect to Syntax and Semantics Occurs during the execution of code at runtime Detected by compiler at the time of code development Not detected by the compiler but are identified at the time of code execution Fixed at the time of code development Fixed after code is executed and error gets identified Examples: Missing ; , Missing braces, Missing parentheses, Undefined Identifier Examples: Divide by Zero, Infinite Loop, Wrong Input by the user, I/O errors, Undefined Object errors We cannot run the code successfully till we correct these errors Stop the program from getting desired results Example Code: main(){ Int x=10; cout<<x } Output: error at line 3:8: ; missing Example Code: main(){ int a=10; int b=0; cout<<a/b; } Output: Floating Point Exception 41
  • 43. EXCEPTION INTRODUCTION • An exception is a problem that arises during the execution of a program • Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution • A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero • Exceptions provide a way to transfer control from one part of a program to another 43
  • 44. EXCEPTION INTRODUCTION CONTD… • C++ exception handling is built upon three keywords: try, catch, and throw • try − • A try block identifies a block of code for which particular exceptions will be activated • It's followed by one or more catch blocks • throw − • Used to throw an exception • Also used to list the exceptions that a function throws, but doesn’t handle itself • This is done using a throw keyword • catch − • represents a block of code that is executed when a particular exception is thrown • The catch keyword indicates the catching of an exception 44
  • 45. EXCEPTION INTRODUCTION CONTD… • Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords • A try/catch block is placed around the code that might generate an exception • Code within a try/catch block is referred to as protected code 45
  • 46. EXCEPTION INTRODUCTION CONTD… • Syntax: try { // protected code } catch( ExceptionName e1 ) { // catch block } catch( ExceptionName e2 ) { // catch block } catch( ExceptionName eN ) { // catch block } 46
  • 47. TYPES OF EXCEPTIONS • There are two types of exceptions: • Synchronous – • Exception handling mechanism can handle only Synchronous Errors • These exceptions are handled by try/catch • They have a termination model – once the control is thrown from the try block the control never returns back • Asynchronous • Cannot be handled by exception handling mechanisms in C++ • Hardware failures can be treated under this category • Example: • program’s control, Disc failure, keyboard interrupts etc., 47
  • 48. WHY EXCEPTION HANDLING? • Separation of Error Handling code from Normal Code • Functions/Methods can handle any exceptions they choose • Grouping of Error Types 48
  • 49. EXCEPTION HANDLING EXAMPLE #include <iostream> 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 n"; } cout << "After catch (Will be executed) n"; return 0; } 49
  • 50. IMPORTANT POINTS REGARDING EXCEPTION HANDLING • There is a special catch block to catch all exceptions • Implicit type conversion doesn’t happen for primitive types • If an exception is thrown and not caught anywhere, the program terminates abnormally • A derived class exception should be caught before a base class exception • C++ library has a standard exception class which is base class for all standard exceptions • In C++, all exceptions are unchecked…Compiler doesn’t check whether an exception is caught or not • Can use functions to specify all uncaught exceptions • In C++, try-catch blocks can be nested • When an exception is thrown, all objects created inside the enclosing try block are destructed before the control is transferred to catch block 50
  • 51. SPECIAL CATCH BLOCK EXAMPLE #include <iostream> using namespace std; int main() { try { throw 10; } catch (char *excp) { cout << "Caught " << excp; } catch (...) { cout << "Default Exceptionn"; } return 0; } 51
  • 52. IMPLICIT TYPE CONVERSION DOESN’T HAPPEN FOR PRIMITIVE TYPES #include <iostream> using namespace std; int main() { try { throw 'a'; } catch (int x) { cout << "Caught " << x; } catch (...) { cout << "Default Exceptionn"; } return 0; } 52
  • 53. IF AN EXCEPTION IS THROWN AND NOT CAUGHT ANYWHERE, THE PROGRAM TERMINATES ABNORMALLY #include <iostream> using namespace std; int main() { try { throw 'a'; } catch (int x) { cout << "Caught "; } return 0; } 53
  • 54. A DERIVED CLASS EXCEPTION SHOULD BE CAUGHT BEFORE A BASE CLASS EXCEPTION #include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; // some other stuff try { // Some monitored code throw d; } catch(Base b) { cout<<"Caught Base Exception"; } catch(Derived d) { //This catch block is NEVER executed cout<<"Caught Derived Exception"; } getchar(); return 0; } Note 1: If both base and derived classes are caught as exceptions then catch block of derived class must appear before the base class Note 2: If we put base class first then the derived class catch block will never be reached 54
  • 55. FUNCTION TO SPECIFY THE UNCAUGHT EXCEPTIONS #include <iostream> using namespace std; void fun(int *ptr, int x) { if (ptr == NULL) throw ptr; if (x == 0) throw x; /* Some functionality */ } int main() { try { fun(NULL, 0); } catch(...) { cout << "Caught exception from fun()"; } return 0; } 55
  • 56. NESTED TRY-CATCH BLOCKS #include <iostream> using namespace std; int main() { try { try { throw 20; } catch (int n) { cout << "Handle Partially "; throw; // Re-throwing an exception } } catch (int n) { cout << "Handle remaining "; } return 0; } 56
  • 57. ALL OBJECTS CREATED INSIDE THE ENCLOSING TRY BLOCK ARE DESTRUCTED BEFORE THE CONTROL IS TRANSFERRED TO CATCH BLOCK include <iostream> using namespace std; class Test { public: Test() { cout << "Constructor of Test " << endl; } ~Test() { cout << "Destructor of Test " << endl; } }; int main() { try { Test t1; throw 10; } catch (int i) { cout << "Caught " << i << endl; } } 57
  • 58. PRINCIPLES OF EXCEPTION HANDLING 58
  • 59. PRINCIPLES OF EXCEPTION HANDLING • If you can't handle an exception, don't catch it • Catch an exception as close as possible to its source • If you catch an exception, don't swallow it • Log an exception where you catch it, unless you plan to re-throw it • Use as many typed exceptions as you need, particularly for application exceptions • By fine graining the throws clause, it is self-documenting and becomes evident to the caller that different exceptions have to be handled. • Never throw unchecked exceptions in your methods just because it clutters the method signature • Throw Application Exceptions as checked Exceptions and Unrecoverable System exceptions as unchecked exceptions • Structure your methods according to how fine-grained your exception handling must be 59
  • 61. CHECKED VS UNCHECKED • Checked Exceptions – • Checked Exceptions are those that extend java.lang.Exception. • If your method throws checked exceptions, then the caller is forced to catch these exceptions at compile time or declare in the throws clause of the method • Unchecked Exceptions – • Unchecked exceptions are those that extend java.lang.RuntimeException, generally referred to as runtime exceptions • If your method throws a runtime exception, the caller of the method is not forced to catch the exception or add it to the method signature at compile time 61
  • 63. SPECIFYING EXCEPTIONS • In C++, one can specify the exceptions through functions • The programmer can specify which type of exception he/she wants to throw 63
  • 64. #include<iostream> using namespace std; void test(int x) throw (int, double) { if(x==0) throw 10; else if(x==-1) throw 15.34; } int main() { try{ test(0); test(-1); } catch(int a) { cout<< "Integer caught "<<a; } catch(double d) { cout<< "double caught"<<d; } } EXAMPLE - 1 ON SPECIFYING EXCEPTIONS 64
  • 65. EXAMPLE - 2 ON SPECIFYING EXCEPTIONS #include<iostream> using namespace std; void test() throw (int, double, char, runtime_error) { throw runtime_error("What is happening here??!!"); } Output: Runtime error caught What is happening here??!! int main() { try{ test(); } catch(int a) { cout<< "Integer caught "<<a; } catch(double d) { cout<< "double caught "<<d; } catch(char ch) { cout<< "Character caught "<<ch; } catch(runtime_error r) { cout<< "Runtime error caught "<<r.what(); } } 65
  • 66. EXAMPLE - 3 ON SPECIFYING EXCEPTIONS #include<iostream> using namespace std; void test() throw () { throw 10; } Output: terminate called after throwing an instance of 'int' int main() { try{ test(); } catch(int a) { cout<< "Integer caught "<<a; } catch(double d) { cout<< "double caught "<<d; } catch(char ch) { cout<< "Character caught "<<ch; } catch(runtime_error r) { cout<< "Runtime error caught "<<r.what(); } } 66
  • 67. EXAMPLE - 4 ON SPECIFYING EXCEPTIONS #include<iostream> using namespace std; void test() { throw 10; } NOTE: Not specifying any exceptions Output: Integer caught 10 int main() { try{ test(); } catch(int a) { cout<< "Integer caught "<<a; } catch(double d) { cout<< "double caught "<<d; } catch(char ch) { cout<< "Character caught "<<ch; } catch(runtime_error r) { cout<< "Runtime error caught "<<r.what(); } } 67