0% found this document useful (0 votes)
12 views27 pages

ppt-unit-6-part(1)

This document provides an overview of exception handling in C++, detailing the mechanisms for detecting, throwing, and catching exceptions. It discusses the types of exceptions, the use of templates, and the importance of managing exceptions in constructors and destructors. Additionally, it covers advanced topics such as re-throwing exceptions, specifying exceptions, and the relationship between templates and friend functions.

Uploaded by

rutu.bidarkar
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)
12 views27 pages

ppt-unit-6-part(1)

This document provides an overview of exception handling in C++, detailing the mechanisms for detecting, throwing, and catching exceptions. It discusses the types of exceptions, the use of templates, and the importance of managing exceptions in constructors and destructors. Additionally, it covers advanced topics such as re-throwing exceptions, specifying exceptions, and the relationship between templates and friend functions.

Uploaded by

rutu.bidarkar
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
You are on page 1/ 27

Unit VI: Exception Handling

Fundamentals:
• Exceptions are run time anomalies or unusual conditions that a
program may encounter while executing.
• Anomalies might include conditions such as division by zero, access
to an array outside of its bounds, or running out of memory or disk
space.
• When a program encounters an exceptional condition, it is important
that it is identified and dealt with effectively.
• ANSI C++ provides built-in language features to detect and handle
exceptions which are basically run time errors.
• 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 suggest a separate error handling code that performs
the 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).
• The error handling code basically consists of two segments, one to
detect errors and to throw exceptions, and the other to catch the
exceptions and to take appropriate actions.
• Exceptions are of two kinds:
A. Synchronous exceptions:
1. “out-of-range index” error
2. “over-low” error
B. Asynchronous exceptions:
Errors caused by events beyond control (such deke keyboard interrupts)
Simple Exception Handling:
C++ exception handling mechanism is
basically built upon three keywords,
• Try: Used to preface a block of
statements.
• Throw: Throws exception in try
block.
• Catch: 'catches' the exception thrown'
by the throw statement and handles it
appropriately.
Throwing Mechanism:
• When an exception that is desired to be handled is detected, it is thrown using the
throw statement in one of the following forms:
throw (exception);
throw exception;
throw; /used for rethrowing an exception
• The operand object exception may be of any type, including constants.
• When an exception is thrown, it will be caught by the catch statement associated
with the try block.
• That is, the control exits the current try block, and is transferred to the catch block
after that try block.
• Throw point can be in a deeply nested scope within a try block or in a deeply nested
function call. in any case, control is transferred to the catch statement.
Catching Mechanism:
• A catch block looks like function definition and
is of the form
1. Type: indicates the type of exception. catch(type arg)
{
2. Arg: an optional parameter name. //Statements for
• Due to mismatch, if an exception is not caught, //managing exceptions
abnormal program termination will occur. }
• It is important to note that the catch block is
simply skipped if the catch statement does not
catch an exception.
Divide by Zero Exception
• Dividing a number by Zero is a mathematical error (not defined) and
we can use exception handling to gracefully overcome such
operations.
• If you write a code without using exception handling then the output
of division by zero will be shown as infinity which cannot be further
processed.
• We can handle this exception in a number of different ways, some of
which are listed below:
1. Using the runtime_error class
2. Using User defined exception handling
3. Using Stack Unwinding
Multiple Catch Statements
• It is possible that a program segment has more than
one condition to throw an exception
• When an exception is thrown, the first handler that
yields a match is executed.
• After executing the handler, the control goes to the first
statement after the last catch block for that try.
• It is possible that argument of several catch statements
match the type of an exception. In such cases, the first
handler that matches the exception type is executed.
Catch all exceptions
• In some situations, we may not be able to anticipate all possible types of
exceptions and therefore may not be able to design independent catch
handlers to catch them.
• In such circumstances, we can force a catch statement to catch all
exceptions instead of a certain type alone.
• This could be achieved by defining the catch statement using ellipses as
follows:
Catch(…)
{
//Statement for processing
// all exceptions
}
Re-throwing an Exception
• A handler may decide do without when exception caught without processing
it. In such situations, we may simply invoke throw without any arguments.
• his causes the current exception to be thrown to the next enclosing try/catch
sequence and is caught by a catch statement listed after that enclosing try
block.
• When an exception is rethrown, it will not be caught by the same catch
statement or any other catch in that group. Rather, it will be caught by an
appropriate catch in the outer try/catch sequence only
• .A catch handler itself may detect and throw an exception. Here again, the
exception thrown will not be caught by any catch statements in that group.
It will be passed on to the next outer try/catch sequence for processing.
Specifying Exception
• It is possible to restrict a function to throw only certain specified
exceptions. This is achieved by adding a throw list clause to the
function definition.
• The general form of using an exception specification is:
type function (arg-list) throw (type-list)
{
//function body
}
• The type-list specifies the type of exceptions that may be thrown.
• Throwing any other type of exception will cause abnormal program
termination.
Exception in Constructor and Destructor
• If an exception is thrown while executing a constructor routine, as
object is not yet fully constructed; its destructor would not be called
once the program control goes out of the context.
• If we allow the exception to be handled inside main then we would
not be able to prevent the memory leak situation that we discussed
earlier.
• Thus, we must catch the exception within the constructor block so that
we get the chance to free up any reserved memory space.
• However, we must simultaneously rethrow the exception to be
appropriately handled inside the main block.
Exception and Inheritance
• Inheritance allows a class to inherit properties and behaviors from
another class.
• When it comes to exceptions, you might have a base exception class,
and then create more specific exception classes that inherit from it.
• This helps in organizing and handling different types of exceptions in
a more structured way.
class MyBaseException(Exception):
pass

class CustomException1(MyBaseException):
pass

class CustomException2(MyBaseException):
pass
Templates
• Templates in C++ is defined as a blueprint or formula for creating a
generic class or a function.
• Simply put, you can create a single function or single class to work
with different data types using templates.
• A keyword “template” in C++ is used for the template’s syntax and
angled bracket in a parameter (t), which defines the data type variable.
The Power of Templates
• Code Reuse and Efficiency
• Flexibility and Adaptability
• Error Reduction
• Maintainability and Readability
• Makes generalization for APIs
• Provides better documentation
Template
Types of Templates in C++
• There are two types of templates in C++:
Function template
Class templates

A function template in C++ is a single function template that works


with multiple data types simultaneously, but a standard function works
only with one set of data types
Function Template syntax

The function template syntax is similar to that of the class template


except that we are defining function instead of classes. We must use
template parameter T as and when necessary in function body and in its
argument list.
Overloading Function Templates
• The name of the function templates are the same but called with
different arguments is known as function template overloading.
• If the function template is with the ordinary template, the name of the
function remains the same but the number of parameters differs.
• When a function template is overloaded with a non-template function,
the function name remains the same but the function’s arguments are
unlike.
Class Templates
• Similar to function templates, we can use class templates to create a
single class to work with different data types.
• Class templates come in handy as they can make our code shorter and
more manageable.
• A class template starts with the keyword template followed by
template parameter(s) inside <> which is followed by the class
declaration.
Non type parameters
• A non-type template argument provided within a template argument
list is an expression whose value can be determined at compile time.
Such arguments must be constant expressions, addresses of functions
or objects with external linkage, or addresses of static class members.
Non-type template arguments are normally used to initialize a class or
to specify the sizes of class members.
• For non-type integral arguments, the instance argument matches the
corresponding template parameter as long as the instance argument has
a value and sign appropriate to the parameter type.
Template and friends Generic 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 template class.
The type name and export keywords
template<class T> class A
{
T::x(y);
typedef char C;
A::C d;
}
• The ‘typename’ keyword is primarily used in template programming to
indicate that a dependent name should be treated as a type. It helps the
compiler understand that a dependent name is a type, especially when
dealing with nested types within templates.
• The ‘export’ keyword is newer and specifically related to modules, which is
a feature introduced in C++20.
Thank You

You might also like