SlideShare una empresa de Scribd logo
1 de 68
Established as per the Section 2(f) of the UGC Act, 1956
Approved by AICTE, COA and BCI, New Delhi
Templates &
Exception Handling in C++
N i m r i t a K o u l
N i m r i t a . k o u l @ r e v a . e d u . i n
C ++ TEMPLATES - OUTLINE
• Quick Recap
• What are Templates?
• Why use templates?
• Function Templates
• Class Templates
• Summary
• Programs
EXCEPTION HANDLING-
OUTLINE
• What is an Exception?
• How is it Handled?
• What are try, catch and throw
• Handling derived class exceptions
• Programs
RECAP: FEATURES OF C++
Image Source: https://dataflair.com
APPLICATIONS OF C++PROGRAMMING
Source: www.sitebay.com
PLATFORM INDEPENDENCE
C++ TEMPLATES
DEFINITION
A template is a pattern or amold, that serves as a guide for manufacture of some articles.
DOCUMENT TEMPLATES
MORE TEMPLATES
TEMPLATES FOR PROGRAMMING -GENERIC PROGRAMMING
WHY GENERIC PROGRAMMING?
1. With a strongly-typed language we need to write different versions of a function that does same operations
ondifferent types ofinput parameters.
2. This leads tolargecode(code bloat), canbe tedious, error prone andtime-consuming.
So what is the
solution?
SOLUTION IS TO USE TEMPLATES
USE OF TEMPLATES FOR FUNCTIONS AND CLASSES ALLOWS US TO WRITE THE
CODE OF THESE FUNCTIONS AND CLASSES WITHOUT EXACT SPECIFICATION OF
THE DATATYPES ON WHICH THESE FUNCTIONS OR CLASSES OPERATE.
THE DATATYPES CAN BE SPECIFIED LATER WHEN THESE FUNCTIONS OR CLASSES ARE
ACTUALLY USED.
THE COMPILER GENERATES A DIFFERENT CODE FOR EACH DATATYPE OF THE
PARAMETERS PASSED BY THE USER DURING ACTUAL USE OF THE TEMPLATE.
WHEN TO USE TEMPLATES?
Candidate functions for templates are those whose implementation remains
invariantover a set ofinstances.
That is, the algorithmic behavior of the code is the same, independent of the
typeof objects thealgorithmis processing.
FUNCTION TEMPLATES CLASS TEMPLATES
DEFINING A FUNCTION TEMPLATE
keyword template always begins a definition and declaration of a function template
<> brackets contain a list of template parameters
keyword ’typename’ or ‘class’ tells the compiler that
what follows is the name of a type
To use the template function you call it with the
required type in angle-brackets.
The compiler will generate a new function for each
new type parameter you supply
IMPLICIT DEDUCTION AND EXPLICIT SPECIFICATION OF RETURN TYPE OF TEMPLATE
In many cases the
template type
can be deduced
from the
invocation of the
function
For example min has two
arguments and a return type
all of the same type.
In the call min(10,20) both
arguments are integers,
therefore the compiler can
deduce that typename
T maps onto int
If it cannot deduce the type
from the argument –
e.g. min (10, 20.9), then a
compiler error message is
generated. This can be
resolved by forcing the type
using explicit instantiation
DATATYPES IN TEMPLATE DEFINITION AND USE, MUST MATCH
EXPLICIT SPECIFICATION OF RETURN TYPE
WHAT HAPPENS IN THE BACK GROUND OF TEMPLATE PROCESSING
New code is generated for each
new type that the compiler
encounters.
The compiler uses the template
code to generate a new
function with the template
parameter replaced by the
supplied type.
A template instance is only created
once.
If multiple calls
to min with int or double arguments
are encountered (or any type for
that matter) then still only one set
of object code is created per
translation unit.
TEMPLATE FUNCTIONS CAN BE OVERLOADED
EXAMPLES – TEMPLATE FUNCTION TO FIND LARGEST OF TWO NUMBERS
OUTPUT
EXAMPLE 2: SWAP DATA USING FUNCTION TEMPLATES
CONTD.
OUTPUT
CLASS TEMPLATES
1. Whenever you Need To
Implement A Generic Class That
Performs Similar Operations On
Different Types Of Data.
Use A Template Class.
2.This Way You Do Not Need To
Create A Different Class For Each
Data Type. Or You Do Not Need To
Create Different Member Variables
And Functions Within A Single Class
For Different Data Types.
3. Advantage is that using
template class reduces code size,
and make code easy to maintain
as any change will need to be
done only on the template.
4. Class templates make it easy
to reuse the same code for all
data types
HOW TO DECLARE A CLASS TEMPLATE?
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.
HOW TO CREATE OBJECT OF TEMPLATE CLASS
EXAMPLE –SIMPLE CALCULATOR
ADVANTAGES OF TEMPLATES
Utility: High utility when we combine it with function overloading and multiple inheritances.
Less Redundancy: The same template once defined can be used for several data types. For
example, if we want to find the area of a rectangle with parameters entered as integer values as
well as floating-point values, we can effortlessly achieve this task with the implementation of
templates without having to create separate functions for integer and floating point data
Reduced Programming Effort: Drastically reduces the programming effort on the user’s end as the
same fragment of code can be used for multiple data types
Reusability and Flexibility: Same fragment of code can be used for multiple data types, providing
flexibility at the user-end to enter any type of data.
TEMPLATE PROGRAMS ON IDE
EXCEPTION HANDLING
Source: www.dataflair.com
EXCEPTION IS AN OCCURRENCE THAT IS NOT NORMAL OR EXPECTED
EXAMPLE
1. Suppose you write aC++ program todivide two integers, it willwork perfectly wellnormally exceptwhen
thedenominatoriszerobecause that resultis mathematicallyundefined. So your compiler doesn’t
knowwhat todo inthis case and justhaltstheprogramorcrashes.
2. To prevent your program from crashing, youcanwritesomecodetotellthecompilerwhattodoin case
this situation arises. This is called exceptionhandling.
SO, WHAT IS AN EXCEPTION?
Exception - > An unexpected problem that occurs during the execution of a program and makes
the program crash
This problem arises because your program tries to do something that is not mathematically or
logically permissible. E.g. trying to divide by zero, trying to access 11th value in an array whose
maximum size is just 10, trying to read from a file that does not exist etc
Writing code in order to maintain the normal flow of the execution of the program when an
exception occurs is known as “Exception Handling”.
EXCEPTION HANDLING CYCLE
EXCEPTION HANDLING IN C++
Image Source: www.dataflair.com
TRY AND CATCH BLOCKS
In C++, exception handling is provided by using three constructs or keywords;
namely, try, catch and throw.
try block – The try keyword specifies the particular block of code in which the
programmer finds that exception handling needs to be implemented.
catch block -The catch keyword indicates that the C++ compiler has caught an
exception
Block of code that provides a way to handle the exception is called “exception
handler”.
The ‘throw’ keyword throws an exception to be handled by the user in other function
or by compiler.
GENERAL EXCEPTION HANDLER
try{
//code likelyto give exception
}catch(exception e){
//codeto process exception e
}
The code that is likely to throw exceptions is enclosed in the
“try” block
The try block can also contain a “throw” statement to
explicitly throw exceptions. The “throw” statement
consists of a keyword “throw” followed by a parameter
which is the exception name. This parameter is then
passed to the catch block
The exception thrown in the “try” block is passed on to
the “catch” block. The catch block contains the code to
process the thrown exception. It can contain merely a
message or an entire code block to process the exception
such that the normal flow of the program is not hindered
MULTIPLE CATCH BLOCKS
We can have multiple catch blocks
wherein each catch block provides
processing for each of the
exceptions generated in try block.
SYNTAX OF THROW STATEMENT
The ‘throw’
keyword throws an
exception to be
handled by the user
in other function or
by compiler.
SUMMARY
HIERARCHY OF EXCEPTIONS CLASS STD:: EXCEPTION IN C++
TYPES OF EXCEPTIONS IN C++
DIVISION BY ZERO WITHOUT EXCEPTION HANDLING
EXAMPLE – DIVISION BY ZERO
OUTPUT
Output:
Exception– Divisionby zero!!
CATCHING BASE AND DERIVED CLASSES AS EXCEPTIONS
We have learnt about inheritance in C++.
We have learnt about base and derived classes.
Our program can get an exception in both a base class and a derived class
To catch an exception for both base and derived class, we should put catch block
of derived class before the base class. Otherwise, the catch block of derived class
will never be reached
if we change the
order of catch
statements then
both catch
statements
become reachable
This modified program
prints “Caught Derived
Exception”
DEFINING NEW EXCEPTIONS
You can define your own exceptions by inheriting and
overriding exception class functionality.
OPPORTUNITIESAT SCHOOL OF CIT REVA
UNIVERSITY
OPPORTUNITIES AT SCHOOL OF CIT, REVA UNIVERSITY
• B.Tech(CSE)
• B.Tech(CS & IT)
• B.Tech(AI & ML)
• B.Tech(ISE)
• M.Tech( CSE)
• M.Tech (AI)
• Hackathons
• WorkshopsandSkill
• Development Programs
• International Internships andProject Expos
Latest Industry Oriented Curriculum -
• ProgrammingTechnologies -Cprogramming,Python
Programming,
Java Programming,R Programming etc.
• Web Technologies – PHP,Perl, Java Script, NodeJS,
Angular JSetc.
• Machine Learning, Deep Learning,
Blockchain,CloudComputing,Mobile
Application Development, DevOps,
Wireless and Sensor Networks
And manymore…
REFERENCES
• https://simplesnippets.tech/cpp-exception-handling/
• https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
• https://www.geeksforgeeks.org/exception-handling-c/
• https://www.tutorialspoint.com/catching-base-and-derived-classes-exceptions-in-cplusplus
• https://www.geeksforgeeks.org/g-fact-60/
EXCEPTION HANDLING PROGRAMS
THANK YOU

Más contenido relacionado

La actualidad más candente

9781111530532 ppt ch13
9781111530532 ppt ch139781111530532 ppt ch13
9781111530532 ppt ch13Terry Yoast
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10Terry Yoast
 
9781111530532 ppt ch06
9781111530532 ppt ch069781111530532 ppt ch06
9781111530532 ppt ch06Terry Yoast
 
Swift 2.0: Apple’s Advanced Programming Platform for Developers
Swift 2.0: Apple’s Advanced Programming Platform for DevelopersSwift 2.0: Apple’s Advanced Programming Platform for Developers
Swift 2.0: Apple’s Advanced Programming Platform for DevelopersAzilen Technologies Pvt. Ltd.
 
9781439035665 ppt ch04
9781439035665 ppt ch049781439035665 ppt ch04
9781439035665 ppt ch04Terry Yoast
 
Ooabap notes with_programs
Ooabap notes with_programsOoabap notes with_programs
Ooabap notes with_programsKranthi Kumar
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
9781111530532 ppt ch03
9781111530532 ppt ch039781111530532 ppt ch03
9781111530532 ppt ch03Terry Yoast
 
Solutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchSolutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchAlbern9271
 
Android Open source coading guidel ine
Android Open source coading guidel ineAndroid Open source coading guidel ine
Android Open source coading guidel inePragati Singh
 
9781111530532 ppt ch04
9781111530532 ppt ch049781111530532 ppt ch04
9781111530532 ppt ch04Terry Yoast
 
9781111530532 ppt ch07
9781111530532 ppt ch079781111530532 ppt ch07
9781111530532 ppt ch07Terry Yoast
 
Baroda code smell and refactoring
Baroda  code smell and refactoringBaroda  code smell and refactoring
Baroda code smell and refactoringMamata Gelanee
 
9781111530532 ppt ch11
9781111530532 ppt ch119781111530532 ppt ch11
9781111530532 ppt ch11Terry Yoast
 

La actualidad más candente (19)

9781111530532 ppt ch13
9781111530532 ppt ch139781111530532 ppt ch13
9781111530532 ppt ch13
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
9781111530532 ppt ch06
9781111530532 ppt ch069781111530532 ppt ch06
9781111530532 ppt ch06
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Swift 2.0: Apple’s Advanced Programming Platform for Developers
Swift 2.0: Apple’s Advanced Programming Platform for DevelopersSwift 2.0: Apple’s Advanced Programming Platform for Developers
Swift 2.0: Apple’s Advanced Programming Platform for Developers
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
9781439035665 ppt ch04
9781439035665 ppt ch049781439035665 ppt ch04
9781439035665 ppt ch04
 
Ooabap notes with_programs
Ooabap notes with_programsOoabap notes with_programs
Ooabap notes with_programs
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
9781111530532 ppt ch03
9781111530532 ppt ch039781111530532 ppt ch03
9781111530532 ppt ch03
 
Solutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitchSolutions manual for absolute java 5th edition by walter savitch
Solutions manual for absolute java 5th edition by walter savitch
 
Android Open source coading guidel ine
Android Open source coading guidel ineAndroid Open source coading guidel ine
Android Open source coading guidel ine
 
9781111530532 ppt ch04
9781111530532 ppt ch049781111530532 ppt ch04
9781111530532 ppt ch04
 
9781111530532 ppt ch07
9781111530532 ppt ch079781111530532 ppt ch07
9781111530532 ppt ch07
 
Chap04
Chap04Chap04
Chap04
 
Baroda code smell and refactoring
Baroda  code smell and refactoringBaroda  code smell and refactoring
Baroda code smell and refactoring
 
9781111530532 ppt ch11
9781111530532 ppt ch119781111530532 ppt ch11
9781111530532 ppt ch11
 
Android code convention
Android code conventionAndroid code convention
Android code convention
 

Similar a Templates and Exception Handling in C++

Similar a Templates and Exception Handling in C++ (20)

Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
$Cash
$Cash$Cash
$Cash
 
$Cash
$Cash$Cash
$Cash
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)Bb Tequila Coding Style (Draft)
Bb Tequila Coding Style (Draft)
 
6-Error Handling.pptx
6-Error Handling.pptx6-Error Handling.pptx
6-Error Handling.pptx
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxLecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptx
 
Presentation1
Presentation1Presentation1
Presentation1
 
Refactoring legacy code driven by tests - ITA
Refactoring legacy code driven by tests -  ITARefactoring legacy code driven by tests -  ITA
Refactoring legacy code driven by tests - ITA
 
c#.pptx
c#.pptxc#.pptx
c#.pptx
 
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
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
Library management system
Library management systemLibrary management system
Library management system
 
Bca5020 visual programming
Bca5020  visual programmingBca5020  visual programming
Bca5020 visual programming
 

Más de Nimrita Koul

Tools for research plotting
Tools for research plottingTools for research plotting
Tools for research plottingNimrita Koul
 
Natural Language Processing
Natural Language ProcessingNatural Language Processing
Natural Language ProcessingNimrita Koul
 
Shorter bioinformatics
Shorter bioinformaticsShorter bioinformatics
Shorter bioinformaticsNimrita Koul
 
Linear regression analysis
Linear regression analysisLinear regression analysis
Linear regression analysisNimrita Koul
 
Nimrita deep learning
Nimrita deep learningNimrita deep learning
Nimrita deep learningNimrita Koul
 
Nimrita koul Machine Learning
Nimrita koul  Machine LearningNimrita koul  Machine Learning
Nimrita koul Machine LearningNimrita Koul
 
Hands on data science with r.pptx
Hands  on data science with r.pptxHands  on data science with r.pptx
Hands on data science with r.pptxNimrita Koul
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentationNimrita Koul
 

Más de Nimrita Koul (10)

Tools for research plotting
Tools for research plottingTools for research plotting
Tools for research plotting
 
Natural Language Processing
Natural Language ProcessingNatural Language Processing
Natural Language Processing
 
Deeplearning
Deeplearning Deeplearning
Deeplearning
 
Structures in C
Structures in CStructures in C
Structures in C
 
Shorter bioinformatics
Shorter bioinformaticsShorter bioinformatics
Shorter bioinformatics
 
Linear regression analysis
Linear regression analysisLinear regression analysis
Linear regression analysis
 
Nimrita deep learning
Nimrita deep learningNimrita deep learning
Nimrita deep learning
 
Nimrita koul Machine Learning
Nimrita koul  Machine LearningNimrita koul  Machine Learning
Nimrita koul Machine Learning
 
Hands on data science with r.pptx
Hands  on data science with r.pptxHands  on data science with r.pptx
Hands on data science with r.pptx
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentation
 

Último

Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxnuruddin69
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stageAbc194748
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...Health
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksMagic Marks
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 

Último (20)

Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
+97470301568>> buy weed in qatar,buy thc oil qatar,buy weed and vape oil in d...
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 

Templates and Exception Handling in C++

  • 1. Established as per the Section 2(f) of the UGC Act, 1956 Approved by AICTE, COA and BCI, New Delhi Templates & Exception Handling in C++ N i m r i t a K o u l N i m r i t a . k o u l @ r e v a . e d u . i n
  • 2. C ++ TEMPLATES - OUTLINE • Quick Recap • What are Templates? • Why use templates? • Function Templates • Class Templates • Summary • Programs
  • 3. EXCEPTION HANDLING- OUTLINE • What is an Exception? • How is it Handled? • What are try, catch and throw • Handling derived class exceptions • Programs
  • 4. RECAP: FEATURES OF C++ Image Source: https://dataflair.com
  • 7.
  • 9. DEFINITION A template is a pattern or amold, that serves as a guide for manufacture of some articles.
  • 12. TEMPLATES FOR PROGRAMMING -GENERIC PROGRAMMING
  • 13. WHY GENERIC PROGRAMMING? 1. With a strongly-typed language we need to write different versions of a function that does same operations ondifferent types ofinput parameters. 2. This leads tolargecode(code bloat), canbe tedious, error prone andtime-consuming. So what is the solution?
  • 14. SOLUTION IS TO USE TEMPLATES USE OF TEMPLATES FOR FUNCTIONS AND CLASSES ALLOWS US TO WRITE THE CODE OF THESE FUNCTIONS AND CLASSES WITHOUT EXACT SPECIFICATION OF THE DATATYPES ON WHICH THESE FUNCTIONS OR CLASSES OPERATE. THE DATATYPES CAN BE SPECIFIED LATER WHEN THESE FUNCTIONS OR CLASSES ARE ACTUALLY USED. THE COMPILER GENERATES A DIFFERENT CODE FOR EACH DATATYPE OF THE PARAMETERS PASSED BY THE USER DURING ACTUAL USE OF THE TEMPLATE.
  • 15. WHEN TO USE TEMPLATES? Candidate functions for templates are those whose implementation remains invariantover a set ofinstances. That is, the algorithmic behavior of the code is the same, independent of the typeof objects thealgorithmis processing. FUNCTION TEMPLATES CLASS TEMPLATES
  • 17. keyword template always begins a definition and declaration of a function template <> brackets contain a list of template parameters keyword ’typename’ or ‘class’ tells the compiler that what follows is the name of a type To use the template function you call it with the required type in angle-brackets. The compiler will generate a new function for each new type parameter you supply
  • 18. IMPLICIT DEDUCTION AND EXPLICIT SPECIFICATION OF RETURN TYPE OF TEMPLATE In many cases the template type can be deduced from the invocation of the function For example min has two arguments and a return type all of the same type. In the call min(10,20) both arguments are integers, therefore the compiler can deduce that typename T maps onto int If it cannot deduce the type from the argument – e.g. min (10, 20.9), then a compiler error message is generated. This can be resolved by forcing the type using explicit instantiation
  • 19. DATATYPES IN TEMPLATE DEFINITION AND USE, MUST MATCH
  • 21. WHAT HAPPENS IN THE BACK GROUND OF TEMPLATE PROCESSING New code is generated for each new type that the compiler encounters. The compiler uses the template code to generate a new function with the template parameter replaced by the supplied type. A template instance is only created once. If multiple calls to min with int or double arguments are encountered (or any type for that matter) then still only one set of object code is created per translation unit.
  • 22.
  • 23. TEMPLATE FUNCTIONS CAN BE OVERLOADED
  • 24. EXAMPLES – TEMPLATE FUNCTION TO FIND LARGEST OF TWO NUMBERS
  • 25.
  • 27. EXAMPLE 2: SWAP DATA USING FUNCTION TEMPLATES
  • 30. CLASS TEMPLATES 1. Whenever you Need To Implement A Generic Class That Performs Similar Operations On Different Types Of Data. Use A Template Class. 2.This Way You Do Not Need To Create A Different Class For Each Data Type. Or You Do Not Need To Create Different Member Variables And Functions Within A Single Class For Different Data Types. 3. Advantage is that using template class reduces code size, and make code easy to maintain as any change will need to be done only on the template. 4. Class templates make it easy to reuse the same code for all data types
  • 31. HOW TO DECLARE A CLASS TEMPLATE? 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.
  • 32. HOW TO CREATE OBJECT OF TEMPLATE CLASS
  • 34.
  • 35.
  • 36. ADVANTAGES OF TEMPLATES Utility: High utility when we combine it with function overloading and multiple inheritances. Less Redundancy: The same template once defined can be used for several data types. For example, if we want to find the area of a rectangle with parameters entered as integer values as well as floating-point values, we can effortlessly achieve this task with the implementation of templates without having to create separate functions for integer and floating point data Reduced Programming Effort: Drastically reduces the programming effort on the user’s end as the same fragment of code can be used for multiple data types Reusability and Flexibility: Same fragment of code can be used for multiple data types, providing flexibility at the user-end to enter any type of data.
  • 40. EXCEPTION IS AN OCCURRENCE THAT IS NOT NORMAL OR EXPECTED
  • 41. EXAMPLE 1. Suppose you write aC++ program todivide two integers, it willwork perfectly wellnormally exceptwhen thedenominatoriszerobecause that resultis mathematicallyundefined. So your compiler doesn’t knowwhat todo inthis case and justhaltstheprogramorcrashes. 2. To prevent your program from crashing, youcanwritesomecodetotellthecompilerwhattodoin case this situation arises. This is called exceptionhandling.
  • 42. SO, WHAT IS AN EXCEPTION? Exception - > An unexpected problem that occurs during the execution of a program and makes the program crash This problem arises because your program tries to do something that is not mathematically or logically permissible. E.g. trying to divide by zero, trying to access 11th value in an array whose maximum size is just 10, trying to read from a file that does not exist etc Writing code in order to maintain the normal flow of the execution of the program when an exception occurs is known as “Exception Handling”.
  • 43.
  • 45. EXCEPTION HANDLING IN C++ Image Source: www.dataflair.com
  • 46. TRY AND CATCH BLOCKS In C++, exception handling is provided by using three constructs or keywords; namely, try, catch and throw. try block – The try keyword specifies the particular block of code in which the programmer finds that exception handling needs to be implemented. catch block -The catch keyword indicates that the C++ compiler has caught an exception Block of code that provides a way to handle the exception is called “exception handler”. The ‘throw’ keyword throws an exception to be handled by the user in other function or by compiler.
  • 47. GENERAL EXCEPTION HANDLER try{ //code likelyto give exception }catch(exception e){ //codeto process exception e } The code that is likely to throw exceptions is enclosed in the “try” block The try block can also contain a “throw” statement to explicitly throw exceptions. The “throw” statement consists of a keyword “throw” followed by a parameter which is the exception name. This parameter is then passed to the catch block The exception thrown in the “try” block is passed on to the “catch” block. The catch block contains the code to process the thrown exception. It can contain merely a message or an entire code block to process the exception such that the normal flow of the program is not hindered
  • 48. MULTIPLE CATCH BLOCKS We can have multiple catch blocks wherein each catch block provides processing for each of the exceptions generated in try block.
  • 49. SYNTAX OF THROW STATEMENT The ‘throw’ keyword throws an exception to be handled by the user in other function or by compiler.
  • 51. HIERARCHY OF EXCEPTIONS CLASS STD:: EXCEPTION IN C++
  • 53.
  • 54. DIVISION BY ZERO WITHOUT EXCEPTION HANDLING
  • 55.
  • 58. CATCHING BASE AND DERIVED CLASSES AS EXCEPTIONS We have learnt about inheritance in C++. We have learnt about base and derived classes. Our program can get an exception in both a base class and a derived class To catch an exception for both base and derived class, we should put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached
  • 59. if we change the order of catch statements then both catch statements become reachable
  • 60. This modified program prints “Caught Derived Exception”
  • 61. DEFINING NEW EXCEPTIONS You can define your own exceptions by inheriting and overriding exception class functionality.
  • 62.
  • 63. OPPORTUNITIESAT SCHOOL OF CIT REVA UNIVERSITY
  • 64. OPPORTUNITIES AT SCHOOL OF CIT, REVA UNIVERSITY • B.Tech(CSE) • B.Tech(CS & IT) • B.Tech(AI & ML) • B.Tech(ISE) • M.Tech( CSE) • M.Tech (AI) • Hackathons • WorkshopsandSkill • Development Programs • International Internships andProject Expos Latest Industry Oriented Curriculum - • ProgrammingTechnologies -Cprogramming,Python Programming, Java Programming,R Programming etc. • Web Technologies – PHP,Perl, Java Script, NodeJS, Angular JSetc. • Machine Learning, Deep Learning, Blockchain,CloudComputing,Mobile Application Development, DevOps, Wireless and Sensor Networks And manymore…
  • 65.
  • 66. REFERENCES • https://simplesnippets.tech/cpp-exception-handling/ • https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm • https://www.geeksforgeeks.org/exception-handling-c/ • https://www.tutorialspoint.com/catching-base-and-derived-classes-exceptions-in-cplusplus • https://www.geeksforgeeks.org/g-fact-60/