SlideShare a Scribd company logo
1 of 47
Unit7 Templates and Exception Handling
Presented By : Tekendra Nath Yogi
Tekendranath@gmail.com
College Of Applied Business And Technology
Content
– Function templates
– Function templates with multiple arguments
– Class templates
– templates and inheritance
– Exceptional Handling (Try, throw and catch)
– Use of exceptional handling.
2By: Tekendra Nath Yogi
Introduction
• Templates make it possible to use one function or class to handle many
different data types.
• Exceptions provide a convenient, uniform way to handle errors that occur
within classes.
• These features are combined in a single chapter largely for historical reasons:
they became part of C++ at the same time.
3By: Tekendra Nath Yogi
Contd..
• In general if the same operation is to be performed with different data types
then we need to write the same code(function or classes) for different data
types.
• This causes redundant code in the program with only difference in data type.
– For example, if we need to write functions for max finding (function
returns the greater of two values) that support different data types then
need to make functions for all different data types.
• But Templates features of C++ make it possible to use one function or class to
handle many different data types.
• The following program illustrates the need of templates
4By: Tekendra Nath Yogi
Contd..
5By: Tekendra Nath Yogi
What is Template?
• An important feature of c++ which helps to eliminate redundant code by
writing a single generic code that takes data type as argument.
• The templates declared for function are called function templates and those
declared for classes are called class templates. They perform appropriate
operations depending on the data type of the parameters passed to them.
• The template functions are also called generic functions and template class are
also called generic classes because they support any data type.
6By: Tekendra Nath Yogi
Contd..
• Function Template:
– A function template can be used to operate on different types of data by taking
data types as a parameter.
– Template functions are defined by using the keyword template.
7By: Tekendra Nath Yogi
Contd..
• How templates work?
– Templates are expanded at compiler time. The idea is simple, source code contains
only generic function/class, but compiled code may contain multiple copies of
same. function/class.
8By: Tekendra Nath Yogi
Contd..
9By: Tekendra Nath Yogi
Contd..
• Homework: Find minimum of two values by using template function
10By: Tekendra Nath Yogi
Contd..
• Function template with multiple arguments:
– Can be define by specifying more template parameters between the angle brackets
in function template declaration.
– For example:
– In this case, our function template Fmin() accepts two parameters of different
types and returns value of the same type as the first parameter (T) that is passed.
– For example, after that declaration and definition we could call Fmin() with:
11By: Tekendra Nath Yogi
Contd..
12By: Tekendra Nath Yogi
Class Template
• The class template models a generic class which supports similar operation for
different data types. The general form of defining class template is as follows:
13By: Tekendra Nath Yogi
Contd..
• The code indicates that a template is being
declared.
• The keyword template before the class indicates that a class template is being
declared.
• The keyword class inside angle brackets specifies a generic data
type(template_type in this case).
• The identifier template_type is a template parameter that is used as a generic
data type within class. There can be more than one template parameters with
comma separated list with each template type preceded with keyword class.
• The template parameters are replaced by actual data type when the specific
version of the class is created.
14By: Tekendra Nath Yogi
Contd..
• Once a class template is declared, we create a specific instance of the class
using the following syntax:
• Where data_type is the type specified as argument to class template. The data
type specified here is used by the compiler to replace the template type
parameter in the class template definition to create the specific version of the
class.
• If int is used as data type then all the occurrence of the template parameter is
replaced by int.
15By: Tekendra Nath Yogi
Contd..
• If the class template uses multiple template parameters then specific instance
of class is created by passing multiple type arguments as required by the class
template declared as:
• The process of generating a class definition from a class template is called
template instantiation.
• A version of template for a particular template argument is called a
specialization.
16By: Tekendra Nath Yogi
Contd..
• Difference between class template and function template:
– A class template differ from function template in the way they are
instantiated. Calling the function using specific argument type creates a
function but to instantiate a class, we must pass the template arguments
during object declaration.
• A class generated from a class template is a perfectly ordinary class. The class
template does not add any runtime overhead and it does not reduce amount of
code generated but it reduce the redundant code while writing the programs.
17By: Tekendra Nath Yogi
Contd..
18By: Tekendra Nath Yogi
Templates and inheritance
• Similar to inheritance of normal class, the class template can also be
inheritated.
• When creating derived class with template mechanism we can create derived
class with following ways:
– Creating a non-template derived class from a template base class
– Creating a template derived class without the template parameter from the base class
template.
– Creating a template derived class with template parameter from the base class
– Creating a derived class with extra template parameter in the derived class along with the
base class template parameter.
– Creating a template derived class from non-template base class.
19By: Tekendra Nath Yogi
Contd..
Creating a non-template derived class from a template base class:
20By: Tekendra Nath Yogi
Output:
Contd..: Creating a template derived class without the template
parameter from the base class template.
21By: Tekendra Nath Yogi
Output:
Contd..:
Creating a template derived class with template parameter from the base class
22By: Tekendra Nath Yogi
Output:
Contd..: Creating a derived class with extra template parameter in the
derived class along with the base class template parameter.
23By: Tekendra Nath Yogi
Output:
Contd..: Creating a template derived class from non-template base class.
24By: Tekendra Nath Yogi
Output:
Exception Handling
– Exceptional Handling (Try, throw and catch)
– Multiple exceptions
– Exceptions with arguments
25By: Tekendra Nath Yogi
Contd..
• What are exceptions?
– Exceptions are errors that occur at runtime.
– They are caused by a wide variety of exceptional circumstance, such as
division by zero, running out of memory, not being able to open a file,
trying to initialize an object to an impossible value, using an out-of-
bounds index to a array, and etc.
26By: Tekendra Nath Yogi
Contd..
• What is exception handling?
– Detecting unusual or unexpected conditions of the program at run time
and taking preventive measure is called exception handling.
– The purpose of exception handling mechanism is to provide a means to
detect and report an exceptional circumstance to that appropriate action
can be taken.
– In c++, exception handling attempts to increase reliability by designing
system to continue to provide service in spite of the presence of faults.
27By: Tekendra Nath Yogi
Exception handling mechanism
• Exception handling mechanism in C++ is basically built upon
three keywords:
– try,
– throw and
– catch
28By: Tekendra Nath Yogi
Contd..
• try block:
– The keyword try is used to surround a block of statements, which may
generate exceptions or a function called from that code generates
exception. This block of statements is known as try block.
– The try block is responsible for testing the existence of exceptions.
– When an exception exist then the normal program flow is interrupted and
the program control is transferred to the appropriate catch block that
matches the type of the object thrown as exception.
29By: Tekendra Nath Yogi
Contd..
• The syntax of try construct is as follows:
30By: Tekendra Nath Yogi
Contd..
• throw block:
– When a problem is detected during the execution of code within try block,
an exception is raised using keyword throw.
– A temporary object of some type is initialized by throw-expression. The
type of object is used in matching the catch block.
– The syntax of the throw construct is as follows:
throw [obj];
31By: Tekendra Nath Yogi
Contd..
• catch block(exception handler):
– The raised exceptions are handled by the catch block.
– This exception handler is indicated by the keyword catch.
– The catch construct must be used immediately after the try block.
– The syntax of catch construct is as follows:
32By: Tekendra Nath Yogi
Contd..
• A typical exception handling code have the following pattern:
33By: Tekendra Nath Yogi
Contd..
• The code that handles exception should perform the following task:
– Hit the exception (detect the problem causing exception)
– Throw the exception(inform that an error has occurred)
– Catch the exception (receive the error information)
– Handle the exception(take appropriate actions)
• When an exception is raised following sequence of steps are performed
– First, the program searches for a matching handler.
– if any matching handler is found, the program control is transferred to the handler
– if handler is not found the program will call the function terminate().
• If no exception are thrown, the program executes in normal way.
34By: Tekendra Nath Yogi
Contd..
35By: Tekendra Nath Yogi
First Execution:
Second Execution:
Example1:
Contd..• Example2:
36By: Tekendra Nath Yogi
First Execution:
Second Execution:
Multiple exceptions:
• In a program there is a chance of errors occurring more than once
at runtime.
• In such a case, C++ permits to design functions to throw as many
exceptions as needed.
37By: Tekendra Nath Yogi
Contd..
38By: Tekendra Nath Yogi
Example:
Exception with arguments:
• throw objects(exception) with information about the cause of exception.
• The exception with argument helps the programmer to know what bad value
actually caused the exception.
39By: Tekendra Nath Yogi
Contd..
• To throw exception with arguments define the exception class with members.
i.e., Declare exception classes to throw object with information of the cause of
the error.
• The catch block mention type and object to catch and get the object thrown
from the exception as:
40By: Tekendra Nath Yogi
Contd..
41By: Tekendra Nath Yogi
Example:
Why Exception Handling?
• Following are main advantages of exception handling over traditional error
handling.
– Separation of Error Handling code from Normal Code
– Methods can handle any exceptions they choose
– Grouping of Error Types
42By: Tekendra Nath Yogi
Contd..
• Separation of Error Handling code from Normal Code:
– In traditional error handling codes, there are always if else conditions to
handle errors. These conditions and the code to handle errors get mixed up
with the normal flow. This makes the code less readable and maintainable.
With try catch blocks, the code for error handling becomes separate from
the normal flow.
43By: Tekendra Nath Yogi
Contd..
• Methods can handle any exceptions they choose:
– A function can throw many exceptions, but may choose to handle some of
them. The other exceptions which are thrown, but not caught can be
handled by caller. If the caller chooses not to catch them, then the
exceptions are handled by caller of the caller.
In C++, a function can specify the exceptions that it throws using the
throw keyword. The caller of this function must handle the exception in
some way (either by specifying it again or catching it)
44By: Tekendra Nath Yogi
Contd..
• Grouping of Error Types:
– In C++, both basic types and objects can be thrown as exception. We can
create a hierarchy of exception objects, group exceptions in namespaces or
classes, categorize them according to types.
45By: Tekendra Nath Yogi
Homework
• What is template? State and explain the importance of template.
• What is template? Explain the function template with example.
• What is function template? Differentiate it with class template.
• Write a program to find sum of two number with different data types by using
template functions.
• Explain the exception handling with example.
• Discuss different keywords used in exception handling.
• Why do we need exceptions? Explain “exceptions with arguments” with suitable
program.
• What are the advantages of exception handling over conventional error handling.
46By: Tekendra Nath Yogi
Thank You !
47By: Tekendra Nath Yogi

More Related Content

What's hot

Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
Ravi_Kant_Sahu
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
Baljit Saini
 

What's hot (20)

Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
Inheritance
InheritanceInheritance
Inheritance
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Object Oriented Programming With C++
Object Oriented Programming With C++Object Oriented Programming With C++
Object Oriented Programming With C++
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Learn Concept of Class and Object in C# Part 3
Learn Concept of Class and Object in C#  Part 3Learn Concept of Class and Object in C#  Part 3
Learn Concept of Class and Object in C# Part 3
 
Friend function in c++
Friend function in c++Friend function in c++
Friend function in c++
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
 
Java Notes
Java NotesJava Notes
Java Notes
 
2.oop concept
2.oop concept2.oop concept
2.oop concept
 
Oop java
Oop javaOop java
Oop java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
C++ classes
C++ classesC++ classes
C++ classes
 
Oops Concept Java
Oops Concept JavaOops Concept Java
Oops Concept Java
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 

Similar to B.sc CSIT 2nd semester C++ Unit7

c-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.pptc-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.ppt
VinayakHospet1
 

Similar to B.sc CSIT 2nd semester C++ Unit7 (20)

Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
Introducing object oriented programming (oop)
Introducing object oriented programming (oop)Introducing object oriented programming (oop)
Introducing object oriented programming (oop)
 
B.sc CSIT 2nd semester C++ unit-1
B.sc CSIT  2nd semester C++ unit-1B.sc CSIT  2nd semester C++ unit-1
B.sc CSIT 2nd semester C++ unit-1
 
Creational Patterns
Creational PatternsCreational Patterns
Creational Patterns
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
 
Angular2 with TypeScript
Angular2 with TypeScript Angular2 with TypeScript
Angular2 with TypeScript
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
c-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.pptc-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.ppt
 
Chap01
Chap01Chap01
Chap01
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Templates c++ - prashant odhavani - 160920107003
Templates   c++ - prashant odhavani - 160920107003Templates   c++ - prashant odhavani - 160920107003
Templates c++ - prashant odhavani - 160920107003
 
The advantage of developing with TypeScript
The advantage of developing with TypeScript The advantage of developing with TypeScript
The advantage of developing with TypeScript
 
AngularConf2015
AngularConf2015AngularConf2015
AngularConf2015
 
A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...
A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...
A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...
 
Big Data Spain 2018: How to build Weighted XGBoost ML model for Imbalance dat...
Big Data Spain 2018: How to build Weighted XGBoost ML model for Imbalance dat...Big Data Spain 2018: How to build Weighted XGBoost ML model for Imbalance dat...
Big Data Spain 2018: How to build Weighted XGBoost ML model for Imbalance dat...
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 

More from Tekendra Nath Yogi

More from Tekendra Nath Yogi (20)

Unit9:Expert System
Unit9:Expert SystemUnit9:Expert System
Unit9:Expert System
 
Unit7: Production System
Unit7: Production SystemUnit7: Production System
Unit7: Production System
 
Unit8: Uncertainty in AI
Unit8: Uncertainty in AIUnit8: Uncertainty in AI
Unit8: Uncertainty in AI
 
Unit5: Learning
Unit5: LearningUnit5: Learning
Unit5: Learning
 
Unit4: Knowledge Representation
Unit4: Knowledge RepresentationUnit4: Knowledge Representation
Unit4: Knowledge Representation
 
Unit3:Informed and Uninformed search
Unit3:Informed and Uninformed searchUnit3:Informed and Uninformed search
Unit3:Informed and Uninformed search
 
Unit2: Agents and Environment
Unit2: Agents and EnvironmentUnit2: Agents and Environment
Unit2: Agents and Environment
 
Unit1: Introduction to AI
Unit1: Introduction to AIUnit1: Introduction to AI
Unit1: Introduction to AI
 
Unit 6: Application of AI
Unit 6: Application of AIUnit 6: Application of AI
Unit 6: Application of AI
 
Unit10
Unit10Unit10
Unit10
 
Unit9
Unit9Unit9
Unit9
 
Unit8
Unit8Unit8
Unit8
 
Unit7
Unit7Unit7
Unit7
 
BIM Data Mining Unit5 by Tekendra Nath Yogi
 BIM Data Mining Unit5 by Tekendra Nath Yogi BIM Data Mining Unit5 by Tekendra Nath Yogi
BIM Data Mining Unit5 by Tekendra Nath Yogi
 
BIM Data Mining Unit4 by Tekendra Nath Yogi
 BIM Data Mining Unit4 by Tekendra Nath Yogi BIM Data Mining Unit4 by Tekendra Nath Yogi
BIM Data Mining Unit4 by Tekendra Nath Yogi
 
BIM Data Mining Unit3 by Tekendra Nath Yogi
 BIM Data Mining Unit3 by Tekendra Nath Yogi BIM Data Mining Unit3 by Tekendra Nath Yogi
BIM Data Mining Unit3 by Tekendra Nath Yogi
 
BIM Data Mining Unit2 by Tekendra Nath Yogi
 BIM Data Mining Unit2 by Tekendra Nath Yogi BIM Data Mining Unit2 by Tekendra Nath Yogi
BIM Data Mining Unit2 by Tekendra Nath Yogi
 
BIM Data Mining Unit1 by Tekendra Nath Yogi
 BIM Data Mining Unit1 by Tekendra Nath Yogi BIM Data Mining Unit1 by Tekendra Nath Yogi
BIM Data Mining Unit1 by Tekendra Nath Yogi
 
Unit6
Unit6Unit6
Unit6
 
B. SC CSIT Computer Graphics Unit 5 By Tekendra Nath Yogi
B. SC CSIT Computer Graphics Unit 5 By Tekendra Nath YogiB. SC CSIT Computer Graphics Unit 5 By Tekendra Nath Yogi
B. SC CSIT Computer Graphics Unit 5 By Tekendra Nath Yogi
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Recently uploaded (20)

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

B.sc CSIT 2nd semester C++ Unit7

  • 1. Unit7 Templates and Exception Handling Presented By : Tekendra Nath Yogi Tekendranath@gmail.com College Of Applied Business And Technology
  • 2. Content – Function templates – Function templates with multiple arguments – Class templates – templates and inheritance – Exceptional Handling (Try, throw and catch) – Use of exceptional handling. 2By: Tekendra Nath Yogi
  • 3. Introduction • Templates make it possible to use one function or class to handle many different data types. • Exceptions provide a convenient, uniform way to handle errors that occur within classes. • These features are combined in a single chapter largely for historical reasons: they became part of C++ at the same time. 3By: Tekendra Nath Yogi
  • 4. Contd.. • In general if the same operation is to be performed with different data types then we need to write the same code(function or classes) for different data types. • This causes redundant code in the program with only difference in data type. – For example, if we need to write functions for max finding (function returns the greater of two values) that support different data types then need to make functions for all different data types. • But Templates features of C++ make it possible to use one function or class to handle many different data types. • The following program illustrates the need of templates 4By: Tekendra Nath Yogi
  • 6. What is Template? • An important feature of c++ which helps to eliminate redundant code by writing a single generic code that takes data type as argument. • The templates declared for function are called function templates and those declared for classes are called class templates. They perform appropriate operations depending on the data type of the parameters passed to them. • The template functions are also called generic functions and template class are also called generic classes because they support any data type. 6By: Tekendra Nath Yogi
  • 7. Contd.. • Function Template: – A function template can be used to operate on different types of data by taking data types as a parameter. – Template functions are defined by using the keyword template. 7By: Tekendra Nath Yogi
  • 8. Contd.. • How templates work? – Templates are expanded at compiler time. The idea is simple, source code contains only generic function/class, but compiled code may contain multiple copies of same. function/class. 8By: Tekendra Nath Yogi
  • 10. Contd.. • Homework: Find minimum of two values by using template function 10By: Tekendra Nath Yogi
  • 11. Contd.. • Function template with multiple arguments: – Can be define by specifying more template parameters between the angle brackets in function template declaration. – For example: – In this case, our function template Fmin() accepts two parameters of different types and returns value of the same type as the first parameter (T) that is passed. – For example, after that declaration and definition we could call Fmin() with: 11By: Tekendra Nath Yogi
  • 13. Class Template • The class template models a generic class which supports similar operation for different data types. The general form of defining class template is as follows: 13By: Tekendra Nath Yogi
  • 14. Contd.. • The code indicates that a template is being declared. • The keyword template before the class indicates that a class template is being declared. • The keyword class inside angle brackets specifies a generic data type(template_type in this case). • The identifier template_type is a template parameter that is used as a generic data type within class. There can be more than one template parameters with comma separated list with each template type preceded with keyword class. • The template parameters are replaced by actual data type when the specific version of the class is created. 14By: Tekendra Nath Yogi
  • 15. Contd.. • Once a class template is declared, we create a specific instance of the class using the following syntax: • Where data_type is the type specified as argument to class template. The data type specified here is used by the compiler to replace the template type parameter in the class template definition to create the specific version of the class. • If int is used as data type then all the occurrence of the template parameter is replaced by int. 15By: Tekendra Nath Yogi
  • 16. Contd.. • If the class template uses multiple template parameters then specific instance of class is created by passing multiple type arguments as required by the class template declared as: • The process of generating a class definition from a class template is called template instantiation. • A version of template for a particular template argument is called a specialization. 16By: Tekendra Nath Yogi
  • 17. Contd.. • Difference between class template and function template: – A class template differ from function template in the way they are instantiated. Calling the function using specific argument type creates a function but to instantiate a class, we must pass the template arguments during object declaration. • A class generated from a class template is a perfectly ordinary class. The class template does not add any runtime overhead and it does not reduce amount of code generated but it reduce the redundant code while writing the programs. 17By: Tekendra Nath Yogi
  • 19. Templates and inheritance • Similar to inheritance of normal class, the class template can also be inheritated. • When creating derived class with template mechanism we can create derived class with following ways: – Creating a non-template derived class from a template base class – Creating a template derived class without the template parameter from the base class template. – Creating a template derived class with template parameter from the base class – Creating a derived class with extra template parameter in the derived class along with the base class template parameter. – Creating a template derived class from non-template base class. 19By: Tekendra Nath Yogi
  • 20. Contd.. Creating a non-template derived class from a template base class: 20By: Tekendra Nath Yogi Output:
  • 21. Contd..: Creating a template derived class without the template parameter from the base class template. 21By: Tekendra Nath Yogi Output:
  • 22. Contd..: Creating a template derived class with template parameter from the base class 22By: Tekendra Nath Yogi Output:
  • 23. Contd..: Creating a derived class with extra template parameter in the derived class along with the base class template parameter. 23By: Tekendra Nath Yogi Output:
  • 24. Contd..: Creating a template derived class from non-template base class. 24By: Tekendra Nath Yogi Output:
  • 25. Exception Handling – Exceptional Handling (Try, throw and catch) – Multiple exceptions – Exceptions with arguments 25By: Tekendra Nath Yogi
  • 26. Contd.. • What are exceptions? – Exceptions are errors that occur at runtime. – They are caused by a wide variety of exceptional circumstance, such as division by zero, running out of memory, not being able to open a file, trying to initialize an object to an impossible value, using an out-of- bounds index to a array, and etc. 26By: Tekendra Nath Yogi
  • 27. Contd.. • What is exception handling? – Detecting unusual or unexpected conditions of the program at run time and taking preventive measure is called exception handling. – The purpose of exception handling mechanism is to provide a means to detect and report an exceptional circumstance to that appropriate action can be taken. – In c++, exception handling attempts to increase reliability by designing system to continue to provide service in spite of the presence of faults. 27By: Tekendra Nath Yogi
  • 28. Exception handling mechanism • Exception handling mechanism in C++ is basically built upon three keywords: – try, – throw and – catch 28By: Tekendra Nath Yogi
  • 29. Contd.. • try block: – The keyword try is used to surround a block of statements, which may generate exceptions or a function called from that code generates exception. This block of statements is known as try block. – The try block is responsible for testing the existence of exceptions. – When an exception exist then the normal program flow is interrupted and the program control is transferred to the appropriate catch block that matches the type of the object thrown as exception. 29By: Tekendra Nath Yogi
  • 30. Contd.. • The syntax of try construct is as follows: 30By: Tekendra Nath Yogi
  • 31. Contd.. • throw block: – When a problem is detected during the execution of code within try block, an exception is raised using keyword throw. – A temporary object of some type is initialized by throw-expression. The type of object is used in matching the catch block. – The syntax of the throw construct is as follows: throw [obj]; 31By: Tekendra Nath Yogi
  • 32. Contd.. • catch block(exception handler): – The raised exceptions are handled by the catch block. – This exception handler is indicated by the keyword catch. – The catch construct must be used immediately after the try block. – The syntax of catch construct is as follows: 32By: Tekendra Nath Yogi
  • 33. Contd.. • A typical exception handling code have the following pattern: 33By: Tekendra Nath Yogi
  • 34. Contd.. • The code that handles exception should perform the following task: – Hit the exception (detect the problem causing exception) – Throw the exception(inform that an error has occurred) – Catch the exception (receive the error information) – Handle the exception(take appropriate actions) • When an exception is raised following sequence of steps are performed – First, the program searches for a matching handler. – if any matching handler is found, the program control is transferred to the handler – if handler is not found the program will call the function terminate(). • If no exception are thrown, the program executes in normal way. 34By: Tekendra Nath Yogi
  • 35. Contd.. 35By: Tekendra Nath Yogi First Execution: Second Execution: Example1:
  • 36. Contd..• Example2: 36By: Tekendra Nath Yogi First Execution: Second Execution:
  • 37. Multiple exceptions: • In a program there is a chance of errors occurring more than once at runtime. • In such a case, C++ permits to design functions to throw as many exceptions as needed. 37By: Tekendra Nath Yogi
  • 39. Exception with arguments: • throw objects(exception) with information about the cause of exception. • The exception with argument helps the programmer to know what bad value actually caused the exception. 39By: Tekendra Nath Yogi
  • 40. Contd.. • To throw exception with arguments define the exception class with members. i.e., Declare exception classes to throw object with information of the cause of the error. • The catch block mention type and object to catch and get the object thrown from the exception as: 40By: Tekendra Nath Yogi
  • 42. Why Exception Handling? • Following are main advantages of exception handling over traditional error handling. – Separation of Error Handling code from Normal Code – Methods can handle any exceptions they choose – Grouping of Error Types 42By: Tekendra Nath Yogi
  • 43. Contd.. • Separation of Error Handling code from Normal Code: – In traditional error handling codes, there are always if else conditions to handle errors. These conditions and the code to handle errors get mixed up with the normal flow. This makes the code less readable and maintainable. With try catch blocks, the code for error handling becomes separate from the normal flow. 43By: Tekendra Nath Yogi
  • 44. Contd.. • Methods can handle any exceptions they choose: – A function can throw many exceptions, but may choose to handle some of them. The other exceptions which are thrown, but not caught can be handled by caller. If the caller chooses not to catch them, then the exceptions are handled by caller of the caller. In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it) 44By: Tekendra Nath Yogi
  • 45. Contd.. • Grouping of Error Types: – In C++, both basic types and objects can be thrown as exception. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types. 45By: Tekendra Nath Yogi
  • 46. Homework • What is template? State and explain the importance of template. • What is template? Explain the function template with example. • What is function template? Differentiate it with class template. • Write a program to find sum of two number with different data types by using template functions. • Explain the exception handling with example. • Discuss different keywords used in exception handling. • Why do we need exceptions? Explain “exceptions with arguments” with suitable program. • What are the advantages of exception handling over conventional error handling. 46By: Tekendra Nath Yogi
  • 47. Thank You ! 47By: Tekendra Nath Yogi