0% found this document useful (0 votes)
9 views67 pages

Unit-V Oop RBK

The document discusses the concepts of exception handling in C++, including types of errors such as logic and syntactic errors, and the importance of managing exceptions to prevent program crashes and data loss. It explains the mechanism of exception handling using keywords 'try', 'throw', and 'catch', and provides examples of how to implement these features in C++. Additionally, it covers templates in C++, which allow for generic programming by enabling functions and classes to operate with any data type.

Uploaded by

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

Unit-V Oop RBK

The document discusses the concepts of exception handling in C++, including types of errors such as logic and syntactic errors, and the importance of managing exceptions to prevent program crashes and data loss. It explains the mechanism of exception handling using keywords 'try', 'throw', and 'catch', and provides examples of how to implement these features in C++. Additionally, it covers templates in C++, which allow for generic programming by enabling functions and classes to operate with any data type.

Uploaded by

jay thorat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

It is very rare that a program works correctly

first time. It has bugs.


The 2 common types of bugs are logic errors
and syntactic errors.
The logic errors occur due to poor
understanding of the problem and solution
procedure.
The syntactic errors arises due to
poor understanding of the language itself.
Errors can be detected by using
exhaustive debugging and testing procedures.
Errors other than logic and syntax errors are
known as exception.
Exception are runtime anomalies or unusual
conditions that a program may encounter while
executing.
Anomalies includes conditions such as division by
zero, access to an array outside of its bounds, or
running out of memory or disk space.
When an exceptional condition is encountered, it
is important to identify and dealt with effectively.
C++ provides built-in language features to detect
and handle exceptions which are basically run
time errors.
Fundamentals of Exception Handling
Reasons/Sources of Exceptions:

• Resource Failure
• User Actions
• Erroneous Statement
Need of Exception Handling
• When exception occurs at any statement, the
program shows error message and terminate at
the same statement.

• If exception occurs, the data entered by user till


that point won’t be saved. User need to restart
the program. This causes loss of time and efforts.

• In commercial program data transferred from


one place to another place. If exception occurs
data sent will be in invalid state.

• If program performing transactions and program


stops, data will be in inconsistent state that
results into financial loss.
C++ exception handling provides
type- safe, integrated approach, for
with the unusual problems that arise
while executing a program.
Exception are of two kinds-
synchronous exception and
asynchronous exception.
Errors such as “out-of-range index”
and “overflow” belong to synchronous
type exceptions.
The errors that are caused by events beyond
the control of the program(such as keyboard
interrupts) are called asynchronous exception.
Proposed exception handling mechanism in C+
+ is designed to handle only synchronous
exceptions.
The purpose of the exception handling
mechanism is to provide means to detect
and report an “Exceptional circumstance”
so that appropriate action can be taken.
The mechanism suggests a separate error
handling code that performs following tasks.

1. Find the Problem (Hit the Exception)


2. Inform that an error has occurred (Throw the
exception)
3. Receive the Error information (Catch the exception)
4. Take corrective actions (Handle the exception)
It is basically built of three key
words- try, throw and catch.
The keyword try is used to
preface a block of statements
which may generate exception.
It is known as try block.
When an exception is detected,
it is thrown using throw
statement in the try block.
A catch block defined by the
keyword catch ‘catches’ the
exception ‘thrown’ by the throw
statement in the try block, and
handles it appropriately.
Catch block must be
immediately follow after try
block that throws the exception
catch(int x)
#include<iostream> {
using namespace std; cout<<"Exception Caught : x ="<<x;
int main() }
{ cout<<"\n END";
int a,b; return 0;
cout<<"Enter values of a and b \n"; }
cin>>a;
cin>>b;
Output:
int x=a-b;
Enter values of a and b
try
{ 12
if (x!=0) 12
{ Exception Caught : x =0
cout<<"Result (a/x) = "<<a/x; END
}
else
{ Enter values of a and b
throw(x); 20
} 15
} Result (a/x) = 4
END
When an exception that is desired to be
handled is detected, it throws using the
throw statement
◦ throw (exception);
◦ throw exception;
◦ throw;
Code of exception handling is included
in catch blocks.
Catch (type arg)
{
//statement
}
Catches the statement that matches with
the argument.
Due to mismatch, is an exception is not
caught, abnormal program termination will
occur.
Simple Exception Handling-divide by zero
#include<iostream>
using namespace std;
int main()
{
float a,b,c;
try
{
Output:
cout<<"Enter two numbers:";
cin>>a>>b;
if(b==0) nter two numbers:12 0
throw b; Div by Error
else
c=a/b;

cout<<"Answer="<<c<<endl; Enter two numbers:12 6


} Answer=2
catch(float b)
{
cout<<"Div by Error"<<endl;
}
return 0;
}
If a catch block cannot handle the
exception
particular it has caught, you can rethrow
exception.
the
The rethrow expression
(throw without assignment_expression) causes
the originally thrown object to be rethrown.
Because the exception has already been caught at
the scope in which the rethrow expression occurs,
it is rethrown out to the next dynamically enclosing
try block.
Therefore, it cannot be handled by catch blocks at
the scope in which the rethrow expression
occurred.
Any catch blocks for the dynamically enclosing try
block have an opportunity to catch the exception.
#include<iostream> cout<<"Main Start:\n";
using namespace std; try
{
void demo() demo();
{ }
try
{ catch(const char*)
throw "Hello"; {
} cout<<"Caught Exception: Inside
catch(const char*) Main\n";
{ }
cout<<"Caught Exception:
cout<<"Main end:\n"<<endl;
Inside Demo\n";
return 0;
throw; }
} Output:
} Main Start:
int main() Caught Exception:Inside Demo
{ Caught Exception:Inside Main
Main end:
#include <iostream> catch(int ex)
using namespace std; {
int main() cout<<"Outer catch ex="<<ex<<endl;
{
int a; }
Try
{ cout<<"Program ends \n";
try return 0;
{ }
cout<<"Enter a Number";
cin>>a;
if(a==1)
throw 5; Output:
cout<<"try ends a="<<a<<endl; Enter a Number1
Inner catch ex=5
} Outer catch ex=5
catch(int ex) Program ends
{
cout<<"Inner catch ex="<<ex<<endl; Enter a Number 20
throw; try ends a=20
} Program ends
}
We can use Exception handling with class
too. Even we can throw an exception of
user defined class types.
For throwing an exception of say demo
class type within try block we may write.

throw demo();
else if (i == 2)
#include<iostream> throw demo2();
using namespace std; }
class demo1 catch (demo1 d1)
{ {
}; cout << "Caught exception of demo1
class demo2 class \n";
{ }
};
int main() catch (demo2 d2)
{ {
cout << "Caught exception of demo2
for (int i = 1; i <= 2; i++)
class \n";
{ }
try }
{ }
if (i == 1)
throw demo1(); Output:
Caught exception of demo1 class
Caught exception of demo2 class
C++ provides a mechanism to ensure that
a given function is limited to throw only a
specified list of exceptions.
An exception specification at the
beginning of any function acts as a
guarantee to the function's caller that
the function will throw only the
exceptions contained in the exception
specification.
Exception specification syntax
A function with no exception
specification allows all exceptions.
A function with an exception specification
that has an empty type_id_list, throw(),
does not allow any exceptions to be
thrown.
Suppose that class A is one of the types in
the type_id_list of an exception
specification of a function.
That function may throw exception objects
of class A, or any class publicly derived
from class A.
When a function with an exception
specification throws an exception that is
not listed in its exception specification,
the C++ run time does the following:
1. The unexpected() function is called.

2. The unexpected() function calls the


function pointed to by
unexpected_handler.
3. By default, unexpected_handler points
to the function terminate()
You can replace the default
value of unexpected_handler
with the function
set_unexpected().
unexpected() cannot return, it may throw
(or rethrow) an exception.
The function unexpected(), when invoked,
calls the function most recently supplied
as an argument to set_unexpected().
If set_unexpected() has not yet
been called, unexpected() calls
terminate().
The function terminate(), when invoked,
calls the function most recently supplied
as an argument to set_terminate().
If set_terminate() has not yet been
called, terminate() calls abort(), which
ends the program.
You can use set_unexpected() and set_terminate() to
register functions you define to be called
by unexpected() and terminate().
The functions set_unexpected() and set_terminate()
are included in the standard header files.
Each of these functions has as its return type and
its argument type a pointer to function with a void
return type and no arguments.
The pointer to function you supply as the
argument becomes the function called by the
corresponding special function:
the argument to set_unexpected() becomes the
function called by unexpected(), and the
argument
to set_terminate() becomes the function
called by terminate().
#include<exception>
#include<iostream>
using namespace std;
void myhandler()
{
cout << "Inside new terminate handler \n";
abort();
}
int main()
{
set_terminate(myhandler); Output:
try{ Inside try block
cout<<"Inside try block \n"; Inside new terminate handler
throw 100;
}
catch(char a)
{
cout<<"Inside catch block \n";
}
return 0;
}
C++ provides a list of standard exceptions
defined in <exception> which we can use
in our programs.
These are arranged in a parent-child class
hierarchy shown below −
When an exception is thrown, destructors of
the objects (whose scope ends with the try
block) is automatically called before the
catch block gets executed.

Destructors are only called for the


completely constructed objects. When
constructor of an object throws an
exception, destructor for that object is not
called.
Output:-

Constructing an object of
Test Destructing an object of
Test Caught 10
Output:-

Constructing an Object of
Test1 Constructing an Object
of Test2 Destructing an Object
of Test1 Caught 20
If both base and derived classes are caught
as exceptions then catch block of derived
class must appear before the base class.
If we put base class first then the
derived class catch block will never be
reached
catch(base b)
#include<iostream>
{
using namespace std;
cout<<"Caught base exception \n";
class base
}
{
catch(derived d)
};
{
class derived:public base
cout<<"Caught derived exception \n";
{
}
};
return 0;
int main()
}
{
derived d;
try
{
Output:
throw d;
}
Caught base exception
catch(derived d)
#include<iostream>
{
using namespace std;
cout<<"Caught derived exception \n";
class base
}
{
catch(base b)
};
{
class derived:public base
cout<<"Caught base exception \n";
{
}
};
return 0;
int main()
}
{
derived d;
try
{
Output:
throw d;
}
Caught derived exception
TEMPLATE
S
Template: The Power of Templates
Template is a simple and yet very powerful
tool in C++.
The simple idea is to pass data type as a
parameter so that we don’t need to write
the same code for different data types.
For example, a software company may need
sort() for different data types. Rather than
writing and maintaining the multiple codes, we
can write one sort() and pass data type as a
parameter.
C++ adds two new keywords to support
templates: ‘template’ and ‘typename’.
The second keyword can always be
replaced by keyword ‘class’.
Templates are expanded at compiler time.
Compiler does type checking before
template expansion.
Source code contains only function/class,
Compiled code may contain multiple
copies of same function/class.
Data type is mentioned at runtime.
Generic Programming
Templates are the foundation of generic
programming, which involves writing code
in a way that is independent of any
particular type.
In c++ template classes and template
function means of generic programming.
A template is a blueprint or formula for
creating a generic class or a function. The
library containers like iterators and
algorithms are examples of generic
programming and have been developed
using template concept with variety of
datatypes.
Function Templates: We can define a template for a
function. For example, if we have an add() function, we
can create versions of the add function for adding the
int, float or double type values.
Class Template: We can define a template for a class.
For example, a class template can be created for the
array class that can accept the array of various types
such as int array, float array or double array.
A function template works in a similar to
a normal function, with one key
difference.

A single function template can work with


different data types at once but, a single
normal function can only work with one set of
data types.

If you need to perform identical operations


on two or more types of data, you use
function overloading to create two functions
with the required function declaration.

However, a better approach would be to use


function templates because you can perform
the same task writing less and maintainable
code.
A function template starts with the keyword
template followed by template parameter/s
inside< > which is followed by function
declaration.
Syntax:-
template <class typename>
typename(T argument list)
{
//Statements
}
In the above code, T is a template
argument that accepts different data
types (int, float), and class is a keyword.
You can also use keyword typename
instead of class in the above example.
When, an argument of a data type is
passed to someFunction( ), compiler
generates a new version of someFunction()
for the given data type.
#include<iostream>
using namespace std;
value."<<endl;
template<class T>
return 0;
T large(T n1, T n2)
}
{
return(n1>n2)? n1:n2;
Output:
}
int main()
Enter two integers:
{
34
int i1, i2;
4 is larger
float f1,f2;
Enter two floating-point number:
char c1, c2;
2.0 2.5
cout<<"Enter two integers:\n";
2.5 is larger
cin>>i1>>i2;
Enter two characters:
cout<<large(i1, i2)<<" is larger"<<endl;
rg
cout<<"Enter two floating-point number: \n";
r has larger ASCII value.
cin>>f1>>f2;
cout<<large(f1, f2)<<" is larger"<<endl;
cout<<"Enter two characters: \n";
cin>>c1>>c2;
cout<<large(c1, c2)<<" has larger ASCII
overload a function template either by a
non- template function or by another
function template.
If you call the name of an overloaded
function template, the compiler will try to
conclude its template arguments and check
its explicitly declared template arguments.
If successful, it will instantiate a
function template specialization, then
add this
specialization to the set of
candidate functions used in
overload resolution.
The compiler proceeds with overload
resolution, choosing the most appropriate
function from the set of candidate functions.
Non-template functions take precedence
over template functions
#include<iostream>
using namespace std;
template<class T>
void f(T x, T y)
{
cout<<"Template"<<endl;
}
void f(int w, int z)
{
cout<<"Non-Template"<<endl;
}
int main()
{
f(1, 2);
f(2.0, 3.0);
f('1', 'b');
f(1, ‘b');
}

Non-Template
Template
Template
Non-Template
The function call f(1, 2) could match the
argument types of both the template
function and the non-template function.
The non-template function is called because
a non-template function takes precedence
in overload resolution.
The function call f('a', 'b') can only match
the argument types of the template
function. The template function is called.
Argument deduction fails for the function call
f(1, 'b'); the compiler does not generate any
template function specialization and overload
resolution does not take place.
The non-template function resolves this
function call after using the standard
conversion
from char to int for the function argument 'b'.
Like function templates, class templates
are useful when a class defines something
that is independent of the data type.

Can be useful for classes like


LinkedList, BinaryTree, Stack, Queue,
Array, etc.

The relationship between a class template and


an individual class is like the relationship
between a class and an individual object.

An individual class defines how a group of


objects can be constructed, while a class
template defines how a group of classes can
be generated.
template <class
T> class
className
{ …..
public:
T
memVa
r;
T
memFu
nction(T
args);
};
Once a template class is defined as above, we
can create class objects as follows:
#include <iostream>
using namespace std; Output:
template<class T>
class A
Addition of num1 and num2 : 11
{ public:
T num1 = 5;
T num2 = 6;
void add()
{
cout<<"Addition of num1 and num2:"<<num1+num2
<<endl;
}
};
int main()
{
A<int> d;
d.add();
return 0;
}
#include<iostream> Output:
using namespace Constructor Called
std;

template<class T, class U =
char> class A {
public:
T x;
U y;
A() { cout<<"Constructor
Called"<<endl; }
};

int main() {
A<char> a; // This will call
A<char, char>
return 0;
}
A template non-type parameter is a special
type of parameter that does not substitute for
a type, but is instead replaced by a value.
A non-type parameter can be any of
the following:
1. A value that has an integral type
or enumeration
2. A pointer or reference to a class
object
3. A pointer or reference to a
function
4. A pointer or reference to a class
member function
5. std::nullptr_t
Non-type parameters are mainly used
for specifying max or min values or any
other constant value for a particular
instance of a template.
The important thing to note about non-
type parameters is, they must be const.
The compiler must know the value of
non- type parameters at compile time.
Because compiler needs to create
functions/classes for a specified non-
type value at compile time
#include <iostream>
using namespace std;
Example: template<class T, int max>
int arrmin(T arr[], int n)
{
int m=max;
for(int i=0; i<n; i++)
if(arr[i]<m)
m=arr[i];
return m;
Output: }
10 int main()
1 {
int arr1[]={10,20,15,12};
int n1=sizeof(arr1)/sizeof(arr1[0]);
char arr2[]={1,2,3};
int n2=sizeof(arr2)/sizeof(arr2[0]);
cout<<arrmin<int, 10000>(arr1, n1)<<endl;
cout<<arrmin<char, 256>(arr2, n2);
return 0;
}
A template function instantiated with one set of
template arguments may be a friend to one
template class instantiated with the same set
of template arguments. This is also the
relationship between a regular non-template
class and a regular non-template friend
function.
There are four kinds of relationships between
classes and their friends when templates are
involved:
One-to-many: A non-template function may be a
friend to all template class instantiations.
Many-to-one: All instantiations of a template
function may be friends to a regular non-template
class.
One-to-one: A template function instantiated with
one set of template arguments may be a friend to
one template class instantiated with the same set of
template arguments. This is also the relationship
between a regular non-template class and a regular
non-template friend function.
Many-to-many: All instantiations of a template
function may be a friend to all instantiations of the
#include<iostream> void show(test<U> t)
using namespace std; {
template<class T> cout<<"The value of x
class test is:"<<t.x;
{ }
T x; int main()
public: {
void setx() test<int> t;
{ t.setx();
cin>>x; show(t);
} }
template<class U>
friend void show(test<U>t); Output:
}; 5
template<class U> The value of x is:5
The keyword export applies to function
templates, member functions of class
templates, member function templates,
and static data members of class
templates.
export can also be applied to a class
template declaration.
Syntax:-
export template <typename
T> Note:-
keyword export cannot be
combined with inline function.
THANK
YOU !

You might also like