0% found this document useful (0 votes)
6 views15 pages

C++ Generic Functions and Exception Handling

The document explains generic functions and classes in C++, which allow for code reuse with different data types using templates. It also covers exception handling, detailing how to use try, throw, and catch keywords to manage runtime errors effectively. Examples illustrate the implementation of generic functions, classes, and exception handling in C++.

Uploaded by

yousufjosef59
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views15 pages

C++ Generic Functions and Exception Handling

The document explains generic functions and classes in C++, which allow for code reuse with different data types using templates. It also covers exception handling, detailing how to use try, throw, and catch keywords to manage runtime errors effectively. Examples illustrate the implementation of generic functions, classes, and exception handling in C++.

Uploaded by

yousufjosef59
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EXCEPTION HANDLING

◦ A generic function in C++ is a function that


works with different data types without being
rewritten for each one. Instead of writing
separate functions for int, float, double, or
user-defined types, you write one function
template, and the compiler generates the
specific version when needed. Generic
◦ A generic function is created using the
keyword template. The normal meaning of Function
the word, template accurately re ects the
keywords use in C++. It is used to create a
template (or framework) that describes what
a function will do, leaving it to the compiler to
in the details as needed
ONE FUNCTION FOR AVOIDS REPEATING MAKES CODE
MANY DATA TYPES, NO FLEXIBLE, FUNCTION

Why
THE SAME LOGIC,
NEED TO WRITE AUTOMATICALLY
SEPARATE FUNCTIONS
SAME ALGORITHM ADJUSTS TO THE DATA
FOR INT, FLOAT, CAN WORK FOR TYPE YOU PASS.
DOUBLE, ETC.. DIFFERENT DATA

Generic
TYPES.

Functions
AUTOMATICALLY REDUCES MANUAL
CREATES CORRECT OVERLOADING→,NO
VERSION,COMPILER NEED TO WRITE MANY
GENERATES FUNCTION OVERLOADED
FOR INT, FLOAT, ETC., FUNCTIONS WITH
WHEN NEEDED. SAME LOGI
Define of a generic function
◦ Template ret-type func-name (parameter list)
{ // body of function }
◦ In a template, T (or any name you choose) is a placeholder for a data type used by
the function. This placeholder can be used inside the function definition just like a
normal data type.
However, it is only a temporary name. When the program is compiled, the compiler
automatically replaces this placeholder with the actual data type used in the function
call.
◦ Although the keyword class is traditionally used to specify a generic type in a template
declaration, you can also use the keyword typename.
Both keywords work the same way when defining templates.
example

◦ An example of Generic
Function
Generic Class
◦ A generic class (also called a class template) is a class that can work with different
data types without being rewritten.

⭐ Why Generic Classes?


◦ To write one class that works for many data types.
◦ To avoid repeating the same class for int, float, double, etc.
◦ To make data structures flexible.
Define of Generic Class
◦ template class class_name
{ . . . };
◦ In a generic class, T is the placeholder type name. This placeholder is replaced with an
actual data type when an object of the class is created.
If needed, you can define more than one generic type by separating them with
commas.
◦ After defining a generic class, you create a specific object of that class using this form:
class_name<type> object_name;
◦ Here, type is the actual data type the class will work with.
◦ The member functions of a generic class are also automatically generic.
You do not need to write template<...> again for each member function—once the
class is a template, all its member functions become generic by default.
Example 1
#include <iostream> int main() {
using namespace std; Box<int> b1(10); // T = int
template <class T> Box<float> b2(5.5); // T = float
class Box { Box<string> b3("Hello"); // T = string
private:
T value; // T is a placeholder type [Link]();
public: [Link]();
Box(T v) { [Link]();
value = v;
} return 0;
}
void show() {
cout << "Value: " << value << endl;
}
};
Example 2
template <class T1, class T2> int main() {
class Pair { Pair<int, float> p1(10, 3.5);
public: Pair<string, int> p2("Age", 25);
T1 first;
T2 second; [Link]();
[Link]();
Pair(T1 a, T2 b) {
first = a; return 0;
second = b; }
}

void display() {
cout << first << " " << second << endl;
}
};
Generic Function Vs Generic Class

Generic Function Generic Class


A function that works with different data types using A class that works with different data types using
templates. templates.
Template applies to the entire class and all its member
Template applies only to one function.
functions.
Used to build data structures like stack, queue, array,
Used for operations like add, swap, sort, search.
pair, box, etc.

Syntax: template <class T> T func(T a, T b) Syntax: template <class T> class ClassName { ... };

Instantiated when the function is called. Instantiated when an object of the class is created.
More suitable for simple repeated logic. More suitable for complex structures working on data.
Only one function becomes generic. All member functions automatically become generic.
Exception Handling
◦ C++ provides a built-in mechanism to handle errors called exception handling.
It helps detect and respond to run-time errors in a structured way, instead of letting the
program crash.
◦ C++ exception handling uses three keywords:
◦ try – to specify the block of code to monitor for errors.
◦ throw – to signal that an error (exception) has occurred.
◦ catch – to handle the exception and take appropriate action.
How it Works
◦ Try Block:
◦ The try block contains the part of the program you want to monitor for errors.
◦ It can be specific, like monitoring a few statements inside a function,
or broad, like enclosing the entire main() function to monitor the whole program.
◦ The catch Block
When an exception is thrown, it is caught by a corresponding catch [Link] can have
multiple catch blocks associated with a single try.
◦ The catch block that executes depends on the type of [Link] the datatype in a
catch matches the thrown exception, that block executes.
◦ All other catch blocks are bypassed. Inside the catch, you can access the exception
value through a variable (optional).
◦ Any datatype can be caught, including user-defined classes, which are often used as
exceptions.
How it Works
◦ The throw Statement
◦ throw must be executed:Inside the try block, orFrom a function called (directly or
indirectly) within the try [Link] is the value or object you are throwing.
◦ Unhandled Exceptions
◦ If there is no matching catch block for a thrown exception, the program may terminate
abnormally.
◦ In Standard C++, an unhandled exception calls the standard library function terminate().
◦ By default, terminate() calls abort() to stop the program.
◦ You can define your own termination handler if desired.
GeneraL Form
try {
// Code that may throw an exception
}
catch (ExceptionType e) {
// Code to handle the exception
}
◦ ExceptionType specifies the type of exception being caught (e.g., int, float, string, or a
custom class).
◦ The program continues execution after the catch block, avoiding a crash.
Example
#include <iostream> int main() {
using namespace std; try {
divide(10, 2); // no exception
void divide(int a, int b) { divide(5, 0); // exception thrown
if (b == 0) { }
throw 0; // throw an int exception catch (int e) {
} cout << "Error: Division by zero.
Exception code: " << e << endl;
cout << "Result: " << a / b << endl;
}
}

cout << "Program continues after catch."


<< endl;
return 0;
}

You might also like