Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
50 views
39 pages
OOP Unit 5 Notes
Notes of oop unit 5,4,3
Uploaded by
tardesakshi067
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save OOP Unit 5 Notes For Later
Download
Save
Save OOP Unit 5 Notes For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
50 views
39 pages
OOP Unit 5 Notes
Notes of oop unit 5,4,3
Uploaded by
tardesakshi067
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save OOP Unit 5 Notes For Later
Carousel Previous
Carousel Next
Download
Save
Save OOP Unit 5 Notes For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 39
Search
Fullscreen
1[Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. Unit -V Exception Handling and Templates 1. Exception Handling 1.1 Fundamentals of Exceptional Handling Exception han ling is a mechanism used in C++ to deal with runtime errors (exeeptiOAS)hat may occur during program execution, Without exception handling, when an @tror occurs, the program terminates abruptly, which can lead to data loss or an inconsistent stateException handling helps manage such errors by allowing the programjt6 hatidle theinpgracefully and recover without terminating immediately. Common Examples of Exceptions in C++ (C++ exceptions are triggered when an effor or unexpected condition occurs during program execution. Below are four common examples of exceptions 1. Division by Zero + Cause: Occurs When a program, attempts to divide a mumber by zero, which is ‘mathematically undefined. + Explanation:“this typicallyileads to a runtime error or undefined behavior. + Handling: Use a conditional check or throw an exception to handle the error. 2. Array Out-of-Bounds Access +_¢€ause! Happens when a program tries to access an array index that is outside its valid range. + Explanation: This can corrupt memory or cause segmentation fault. + Handling: Use bounds checking or throw an exception if an invalid index is accessed, le Not Found + Cause: Occurs when a program tries to open or read a file that does not exist or is inaccessible.21Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. + Explanation: The file handling functions fail, and the program cannot proceed, + Handling: Check if the file exists before accessing it, or use exception handling to ‘manage the error, 4. Invalid Type Conversion ‘+ Cause: Happens when a program attempts to convert between incompatible types, such. as converting a string to an integer. + Explanation: May result in undefined behavior or runtime errors. + Handling: Validate the input or throw an exception for invalidjeonversioits. For example: int c= a/b; // if b= @, this will generate a runtime error Need for Exception Handling Without exception handling, errors cause the program to fétminate, potentially leading to: + Data loss: If the program crashes before saving user input. ‘+ Inconsistent state: Dataziiight be left in an invalid state, especially in commercial applications, + Financial loss: £9 progtans involving transactions or sensitive data, an error can cause significant problems. How to Handle Exceptions C+ provides three common ways to handle exceptions; 1.4 Remedial. Action: The program tries to fix the issue and continues execution 2 Retry: The program displays the error and prompts the user to correct the mistake, 3. Terminate: The program shows an error message and stops. C++ Exception Handling Keywords C+ uses three keywords for exception handling: 1. try: Defines a block of code that may generate an exception.31Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 2. eattch: Catches and handles the exception thrown by the try block. 3, throw: Used to throw an exception when an error occurs. Structure of try-cateh A basic try-catch block looks like this: try { // Code that may generate an exception + catch (Type variable) { // Code to handle the exception + + The try block contains code that may throw an,exeeption + The catch block catches the throwsiékteption and handles it. + Type is the data type of the exception being thrown(eg., int, string). Key Points: ‘+ Aprogram can haye multiple catch blocks to handle different types of exceptions. + Ifno exception oceutithe catch bl0ek is skipped. + fan exceptiofis thrown, the control jumps directly to the catch block, and the rest of the try bloehais skipped. «he data type oF he thrown exception must match the type in the catch block to ensure proper handlings Exaile: Program to handle exception using class type exception, #include)
using namespace std; // Define a custom exception class class MyException { public: // Constructor to display an error messagealrace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. MyException(const char* msg) { errortlessage = msg; // Function to get the error message const char* getErrormessage() { return errorMessage; private: const char* errorMessage; int main() { try { i mulate an error by €hrowing @) custom exception throw MyException(s"Custom exception occurred!"); } catch (Myexception& e) { // Catch the custg Sception and display the error message coutye using namespace std; int divide(int a, int b) {51Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. if (b == 0) { throw "Division by zero error"; // Throw an exception if // divisor is zero + return a / bj int main() { int numerator, denominator; cout > numerator; cout > denominator; try { int result = divide(numerator, denominator); 11 attemp@divi Sion cout using namespace std; int main() { int e1, sub; float a, b, div, e; try { cout > a >> b; // Throw exception if second number is z ide by zero) if (b == @) throw e; div = a/b; cout using namespace std; int main() { int e1, sub; float a, b, div, @; try ( cout > a >> b; %/ Throw exception if second number is zero (divide by zero) if (b == @) throw e; div = a/b; cout using namespace std; int main() { int a; try { // outer try block try { // Inner try block cout > a3 if (a == 1) throw 53 // Thrdlan inteBer exception cout using namespace std; void subFunction() throw (int) { throw 1@; // Throws an int exception void outerFunction() throw (int) { try { subFunction(); // Calls a } catch (int e) { cout using namespaée std; // UserMieFinkt exfeption class derived from ‘exception class) DemoEXpt : public exception { publ ies void ’showerr() { cout > a >> b; try { if (a
header. This function alloWs you fo set a custom termination handler that will execute instead of the default terminate() function. Example: Custom Termination Handler The following program demonstrates howto set a custom handler for unexpected exceptions #include
#tinclude
using namespace)std; K/ CuspOMterMygPion handler void) myhandler() { cout #include
using namespace std; // User-defined efpeptitn class class Demo€xpt : public exéeption { int vif/v23%j/ Data members to store invalid values publi G7 consyctor to collect error-specific data DefioExpt(int a, int b) { vi = a3 v2 = b5 // Function to display error details void ShowErr() {19] Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. cout > a >> b; try { if (a
using namespace std; class Test { int ids public: Test(int id) : id(id) { cout using namespace std; class Base {}; class Derived : public Base {}; int main() { Derived d; // Object of derived class try { throw d; // Throwing an object of denfved Blass + catch (Derived &d) { // Catchedertad clad First cout ReturnType FunctionName(Parameters) { Function logic ‘template: The keyword used to define a template function. €lass TypeName: This is the placeholder for the data type that will be used.in the function. You can also use typename instead of ss. The type namewill be specified when the funetion is called. ReturnType: The return type of the function, which will be Replaced with the template type during function call, FunctionName: The name of the function being defied. Parameters: The function's parameters, which caibe of the template type. When you call a template function, you provide the actual data type for TypeName in the form of Funct ionName
(arguments)s Benefits of Function Templates: 1 Code Reusabiliff: You}can write one function that works with multiple data types, avoiding code duplication. Flexibility: The same}function can work with different types of data, such as integers, oats, and giser-défined types, with no additional code changes, ‘Type Safety: The compiler ensures that the function is used with compatible data types. Ma ability: Having a single function template makes the code easier to maintain. andlextend, Example 1: Function Template for Sum of Two Values #include
using namespace std; template
21 Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. TempType Add(Temptype a, TempType b) { TempType cs c a+b; return c; int main() { + int p= 4, q = 3, float x = 3.4, y= 1.2, 23 // Call function with int type r= Addcint>(p, 9); cout (x, y); cout (p, q) adds two integers, and Add
(x, y) adds two floating-point numbers, ple 2: Function Template for Finding the Minimum Value in an Array clude
ng namespace std;21 Poce © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. // Function template to find the minimum value in an array template
T findMin(T arr[], int size) { T minVal = arr[@]; // Assume the first element is the minimum for (int i = 1; i for integers, Min
for floats).2 [Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act © Depending on the user's choice (opt, the function either works with an array of integers, or floats to find the smallest number. 2.3 Overloading Function Templates Function overloading is a form of polymorphism in C++, where multiple functions can have the same name but differ in their parameter types or the number of parameters. This allows the programmer to define several functions that perform similar operations but on different types of data, When using function templates, overloading can also be applied to define a function template that works with different data types. How Does Overloading Work with Templates? Ifyou have a normal fun mn (non-template) and a template funetion With the same name, the compiler will use the normal function for exactimatches Gf data f¥pes. If there is no exact match, the template function will be used! For example: #include
using namespace std; void add(int a, int b) { cout void add(Temptype a, TempType b) { Temprype ¢3 ca at; cout ) return @; + + Explanation: © The function add(int, int) is a regular function, so ityill be wed whe the arguments are of type int. © For other types like float, the template fumetion add
dis used. 2.3 Class Template and Non-Type Parameters, In. C++, elass templates are used when we need to createa class that can operate on a variety of data types. A class template allows us t@ define a class whete the data type is pecified at the time of object creation (instantiation), makinglthe class flexible and reusable for different types of data, Class templates are idealyfar generic programming, as they allow the same class to work with different data types without duplicating the code. Class Template Syntax The basic syntax for defining a classitemplate is: template class ChassName { 1p neers i, NenberFunctions + template
: This part defines a template class. The TypeName is a placeholder for a data type that will be specified later when an object of the class is created, ‘+ class ClassName: This defines the name of the class template, The class can now use the TypeName in its data members and member functions to allow flexibility in the types of data it can work with,BilPoge © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. Object Creation for Class Template When creating an object of a class template, we specify the actual data type to be used. The compiler then replaces the template with the specified data type, generating a new class that ‘operates on that data type, ‘The syntax for creating an object of a class template is: ClassName
object_name; + DataType: This is the type of data (such as int, float, char, etc.) thatthe classitemplate will use. + object_name: This is the name of the object created fromthe clasStemplate. Class Template using multiple parameters In C++, a class template can accept multiple template parameters, allowing you to create a class that works with more than one data typedThis feature enables yOu to design classes that can operate on various types of data and support mul le operations that involve these types. ‘Syntax of Class Template with Multiple Parameters: template
class ClassName { // Class defiggrion + TypeVand Type? ate placeholders for data types that will be defined when creating Objects of the class, + You ein haveltiore than two template parameters as needed. Example Program Using Class Template with Multiple Parameters, #include
using namespace std; // Class template accepting two parameters template
class Adder {321 Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. private: Typel first; // First number Type2 second; // Second number public: // Constructor to initialize the numbers Adder(Type1 f, Type2 s) : first(F), second(s) {} 7/ Method to add the two numbers and return the resul Typet add() { return first + second; int main() { // Creating objects of Adder@lass with int and float types Addercint, float> addert(5, 3.5); cout adder2(5.5, 7); jouble + int): " adder3(2.5f, 4.5)5 cout) class ClassName { // Data members and memberfFunctions ‘+ int Size is a non-type parameter, It repréSents/a constant value that must be specified when the class iginstantiated, + Non-type parametersiare often used when you need to define sizes, limits, or other constant values for a classitemplate. 2.4 Template anid Friend Generic Function A template friend function combines the concepts of templates and friend functions. You can declare a friend funtion as a template function to allow it to work with any data type while stithhaving acce§s to the private members of a class. To do thigp 1, The class defines the friend fun: 2. The friend function is also defined as a template, allowing it to work with various data types. Syntax for a Template Friend Function: template
34] Page © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. class ClassName { // Declare the template friend function friend ReturnType FriendFunctionName(ClassName
&) ; // Define the friend function outside the class template
ReturnType FriendFunctionName(ClassName
& obj) { 7/ Function implementation + Example of Template and Friend Function: #include
using namespace std; template
class Box { private: T tength; XX ne oO r unction declaration as template Bo; fi f righd T getArea(BoxcT>& b); // Friend template function oF // Friend template function definition ‘template
T getArea(Box
& b) { return b.length * b.length; // Access private member ‘length’ of Box351Poge © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. int main() { Box
intBox(5); Box
doubleBox(3.5); cout 361 Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. FunctionOrClassDefinition; Example: template
void Swap(tempType& a, tempType& b) { temptype t3 tea; a=; ‘+ typename declares tempType as a generic type. = You e: also use the class keywordsinsteath of typename. ‘There is no functional difference between using class and typenane inithis conteXt. Both are used to specify the type parameter for the template, Second Use: Indicating a Type Name in Nested Classes ‘The typename keywords also used to inform the compiler that a name is a type name rather than an object or variable. This is particularly important in cases where a name is part of a template class or when fecessingypestiésted within templates. Example: template
class MyClass { publite: ‘typename temptype: :Name somedbject; ub Here: + typename tempType: :Name tells the compiler that tempType: : Name is a type (not an object) and should be treated as such, + This is necessary because the compiler might not automatically reco; due to its dependency on the template parameter.371Pege © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 2. export Keyword The export keyword was introduced in earlier versions of C-++ to help with separating the declaration and definition of template classes or functions. It allows you to declare a template in one file and then define it in another file, promoting reusability and cleaner code. Purpose: + The export keyword enables the template to be used across multiple translation units (source files) without requiring the full definition in each file. «Its used to make templates reusable by declaring them in a header fil@while keeping their definitions in a source file However, the export keyword is not widely supported in modern C+ eompilets and has been deprecated. Most modern C+ compilers do n6t,implement it dué to its e8mplexity and lack of widespread use. Today, templates are typieally Weelared ‘aiid, defifed in header files, and export is rarely used in practice. Example (conceptual, as export is not commonly supported): export template
void Swap(T& a, T&b) { ([/ Define the template function with “export Tt tea a=b; b= ty } inthis example; + (export allows the template definition in one file while still being usable in other files thatjinclude the header with the declaration. + However, this syntax is mostly outdated and not widely supported.381 Poce © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 2.6 Difference between Overloaded Functions and Function Templates Aspect Overloaded Function Fanetion Template Definition ‘A feature in C++ where multiple | A generic function that can work with functions with the same name but | any datatype, defined using different parameter lists are | templates. defined. Flexibility Works with specific data types | Works with multiple datalfypes using defined in individual funetion | a single generic definition, definitions, Number of | Requires separate function | Requires only oie generi@pfunction Functions definitions for each data type. | definitiof/forimultipl@data types. Code Limited, as each datatype | High, a8 a sipglefunction can handle Reusability | requires a separate function. frultiple data types. Implementation | Handled by the progfaifimer, [Handled Wby the compiler, which with manual definitions for each type. gentrates type-specific functions from the template at compile time. Performance Usage Slightly faster, as the functionpis: specifically défigned for a single data type, Best) >for situations where funetions need Specific logic for Gifferentdata types. May introduce minor overhead during compilation, as the compiler generates code for each used data type. Best for scenarios where the same logic can be applied to multiple data types. Synitaiy No We of template keyword Defined with the template
or templatectypenane T> keyword.391 Pace © Haris Chaus | ALL RIGHTS ARE RESERVED as per copyright act. 2.7 Difference between Class Template and Function Template Aspect | Class Template Function Template Definition | A template used to define a class that | A template used to define a function can work with multiple data types. | that can work with multiple data types. Purpose | Enables the creation of classes that | Enables the creation of funetions that handle generic types, such as data | can perform the same operation on structures or utility classes ferent data types. Scope of | Provides a blueprint for creating | Provides a mechanism forgereating Use objects that operate on different data types. type-independent functions. Complexity Usually more complex as it deals with multiple member funetions and Simplengas Wy focuseSson a single operation or logic} variables, Usage Used when multiple gmethber | Lised for Single operations like sorting, funetions or data members depend on | seafehing, or arithmetic where only the generic type. thé logic depends on the type. Syntax | Defined using tenplatecclass\yi>) Defined using template
or templatectypename T> before | or templatectypename T> before the class definition? the function definition. Example | Often sed fOy implement data | Often used for algorithms or utilities Usage structures (e.g., vectOi stack, queue). | (e.g., addition, swapping values). Object |JREqUies creating objects of the class | Does not require an object; directly Creation | by gSpetifying the data type at| calls the function with the required runtimes data type.
You might also like
OOP Unit 5 Notes
PDF
No ratings yet
OOP Unit 5 Notes
39 pages
Introduction To Exception, Try and Catch Block
PDF
No ratings yet
Introduction To Exception, Try and Catch Block
10 pages
Week 14 - Exception Handling
PDF
No ratings yet
Week 14 - Exception Handling
14 pages
Exception handling
PDF
No ratings yet
Exception handling
49 pages
Module 5 C++
PDF
No ratings yet
Module 5 C++
6 pages
Module 5 C++
PDF
No ratings yet
Module 5 C++
19 pages
Unit-4 Exception Handling
PDF
100% (1)
Unit-4 Exception Handling
23 pages
UNIT 4-OOPs
PDF
No ratings yet
UNIT 4-OOPs
21 pages
0003 Exception Handling
PDF
100% (1)
0003 Exception Handling
3 pages
Exception Handling in C++
PDF
No ratings yet
Exception Handling in C++
29 pages
Exception Handling(1)
PDF
No ratings yet
Exception Handling(1)
33 pages
PPT12 Exception Handling
PDF
No ratings yet
PPT12 Exception Handling
29 pages
Exception Handling
PDF
No ratings yet
Exception Handling
6 pages
C++ Exception Handling
PDF
No ratings yet
C++ Exception Handling
20 pages
Module 5
PDF
No ratings yet
Module 5
55 pages
Exception Handling
PDF
No ratings yet
Exception Handling
4 pages
exception handling in C++ --- TEAM AKASH
PDF
No ratings yet
exception handling in C++ --- TEAM AKASH
8 pages
Simple Program For Exception Handling Divide by Zero: Algorithm
PDF
No ratings yet
Simple Program For Exception Handling Divide by Zero: Algorithm
6 pages
Exception
PDF
No ratings yet
Exception
3 pages
PPT11
PDF
No ratings yet
PPT11
23 pages
Cpp_UNIT-5
PDF
No ratings yet
Cpp_UNIT-5
12 pages
C++ Exception Handling: Throwing Exceptions
PDF
No ratings yet
C++ Exception Handling: Throwing Exceptions
2 pages
Exceptions in C++
PDF
100% (1)
Exceptions in C++
5 pages
exception handling
PDF
No ratings yet
exception handling
9 pages
Exception handling
PDF
No ratings yet
Exception handling
20 pages
CPP Exceptions Handling
PDF
No ratings yet
CPP Exceptions Handling
4 pages
Oop 11 (Exception Handling)
PDF
No ratings yet
Oop 11 (Exception Handling)
20 pages
C++ Exception Handling Presentation
PDF
No ratings yet
C++ Exception Handling Presentation
6 pages
PPT12
PDF
No ratings yet
PPT12
23 pages
Exchange
PDF
No ratings yet
Exchange
8 pages
Exception Handling
PDF
No ratings yet
Exception Handling
35 pages
Exception Handling in C++
PDF
100% (1)
Exception Handling in C++
15 pages
CPP Exceptions Handling PDF
PDF
100% (1)
CPP Exceptions Handling PDF
4 pages
Exception Handling in C++
PDF
No ratings yet
Exception Handling in C++
4 pages
Adobe Scan 06 May 2024
PDF
No ratings yet
Adobe Scan 06 May 2024
18 pages
Unit 5 Exception
PDF
No ratings yet
Unit 5 Exception
33 pages
CPP Unit-V
PDF
No ratings yet
CPP Unit-V
23 pages
Unit-6
PDF
No ratings yet
Unit-6
34 pages
OOP - Chapter 10 Exception Handling
PDF
No ratings yet
OOP - Chapter 10 Exception Handling
22 pages
Exception Handling in C++
PDF
No ratings yet
Exception Handling in C++
30 pages
CPP UNIT-V
PDF
No ratings yet
CPP UNIT-V
23 pages
Exception Handling
PDF
No ratings yet
Exception Handling
32 pages
OOP Lab 13
PDF
No ratings yet
OOP Lab 13
12 pages
Exceptions in C
PDF
100% (1)
Exceptions in C
5 pages
Oop Notes Unit 5
PDF
No ratings yet
Oop Notes Unit 5
21 pages
Exception Handling
PDF
No ratings yet
Exception Handling
13 pages
Exceptions: This Webpage Is Not Available
PDF
No ratings yet
Exceptions: This Webpage Is Not Available
3 pages
Exception Handling
PDF
No ratings yet
Exception Handling
4 pages
Exception Handling BY Ms. P.Jayalakshmi, Ap/Cse Ms. J.Gowthamy, Ap/Cse
PDF
No ratings yet
Exception Handling BY Ms. P.Jayalakshmi, Ap/Cse Ms. J.Gowthamy, Ap/Cse
9 pages
Unit 5
PDF
No ratings yet
Unit 5
10 pages
Exception Handling in C++
PDF
100% (1)
Exception Handling in C++
8 pages
Oop Unit 5
PDF
No ratings yet
Oop Unit 5
34 pages
Try_Catch_Throw_C++
PDF
No ratings yet
Try_Catch_Throw_C++
6 pages
Clas-PPT-C++-Exception Handling
PDF
No ratings yet
Clas-PPT-C++-Exception Handling
26 pages
Exception Handling
PDF
No ratings yet
Exception Handling
10 pages
oops4
PDF
No ratings yet
oops4
45 pages
C++ Exception Handling
PDF
No ratings yet
C++ Exception Handling
8 pages