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

Exception Handling

The document discusses exception handling in C++, highlighting its importance in managing runtime errors caused by various exceptional circumstances. It explains the syntax and structure of exception handling using keywords like 'throw', 'catch', and 'try', and emphasizes the separation of error handling code from normal code for better readability. Additionally, it outlines the benefits of using exceptions, such as grouping error types and the ability to handle errors at different program levels.
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)
3 views27 pages

Exception Handling

The document discusses exception handling in C++, highlighting its importance in managing runtime errors caused by various exceptional circumstances. It explains the syntax and structure of exception handling using keywords like 'throw', 'catch', and 'try', and emphasizes the separation of error handling code from normal code for better readability. Additionally, it outlines the benefits of using exceptions, such as grouping error types and the ability to handle errors at different program levels.
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/ 27

Exceptions

CLO-3, PLO-2, C4

1
Exceptions

• Object Oriented approach to handle errors which are


generated by C++ classes or related code.

• These are the errors that may also occur at runtime.

• They are caused by a wide variety of exceptional


circumstance, such as running out of memory, not
being able to open a file, trying to initialize an object to
an impossible value, or using an out-of-bounds index to
a vector.
Exceptions
It becomes complicated even further when an
application uses class libraries. Because;
A class library and the application that makes use of it
are often created by separate people: the class library by
a vendor and the application by a programmer who buys
the class library. This makes it even harder to arrange for
error values to be communicated from a class member
function to the program that’s calling the function.

The problem of communicating errors from deep within


class libraries is probably the most important problem
solved by exceptions.
Exceptions

Exception Syntax
Imagine an application that creates and interacts with objects of
a certain class. Ordinarily the application’s calls to the class
member functions cause no problems. Sometimes, however, the
application makes a mistake, causing an error to be detected in a member
function. This member function then informs the application that an error has
occurred. When exceptions are used, this is called throwing an exception. In the
application we install a separate section of code to handle the error.
Exceptions

This code is called an exception handler or catch block; it catches the


exceptions thrown by the member function. Any code in the application that
uses objects of the class is enclosed in a try block. Errors generated in the try
block will be caught in the catch block.
Code that doesn’t interact with the class need not be in a try block.

(Text book)
Exceptions

Fig 14.4 (Text book)


Exceptions

The exception mechanism uses three new


C++ keywords:

throw,
catch, and
try.
Exceptions

try block

The code which can cause an exception is kept


inside a try block.
Then, when the code lead to an error, that error
will get caught inside the catch block.
Exceptions

catch block

catch block is used to catch the error and respond


to the exception. There can be multiple catch
blocks to handle different types of exceptions and
perform different actions when these exceptions
occur.
Exceptions

throw

throw statement is used to throw exceptions


to exception handler i.e. it is used to
communicate information about error. A throw
expression accepts one parameter and that
parameter is passed to handler.
Exceptions

throw statement is used when we explicitly


want an exception to occur, then we can use
throw statement to throw or generate that
exception.
Exceptions

Sequence of Events
Let’s summarize the sequence of events when an exception
occurs:
1. Code is executing normally outside a try block.
2. Control enters the try block.
3. A statement in the try block causes an error in a
member
function.
4. The member function throws an exception.
5. Control transfers to the exception handler (catch block)
Exceptions

Example

main ()
{
int age;
cout<<"Enter your age in years"<<endl;
cin>>age; Output
cout<< " you are " <<age<<" years old" Enter your age in years
<<endl; 44
you are 44 years old
}
Exceptions
Example
main () Output-1
{ Enter your age in years
try 33
{ you are 33 years old
int age;
cout<<"Enter your age in years"<<endl; Output-2
cin>>age; Enter your age in years
if(age>0) { cout<< " you are " <<age<<" years old" <<endl; } -25
else { Operation aborted - invalid value.
throw(age); Age value cannt be: -25
}
} Output-3
catch (int age)
Enter your age in years
{ 0
cout << "Operation aborted - invalid value. \n"; Operation aborted - invalid value.
cout << "Age value cannt be: " << age; Age value cannt be: 0
}
}
xample Multiple exceptions
Exceptions
main () { Output
try { Enter your age in years
int age, xp; 24
cout<<"Enter your age in years"<<endl; cin>>age; you are 24 years old
if(age>0) { cout<< " you are " <<age<<" years old" <<endl; }
else if(age==0)
{ Output
throw(55); Enter your age in years
} 0
else if(age<0) Integer Exception, Ex value is:55
{
throw(3.5f);
}
}
Output
catch(int j) Enter your age in years
{ cout<<"Integer Exception, Ex value is:"<<j<<endl; -77
} Float Exception, Ex value is: 3.5
catch(float m) { cout<<"Float Exception, Ex value is: "<<m<<endl; }
catch(char k) { cout<<"Character Exception, Ex value is: "<<k; }
catch(...) { cout << "Exception: Unknown"; }
}
Exceptions
Example
main () {
try {
int age, xp; double p;
cout<<"Enter your age in years"<<endl; cin>>age; Output
if(age>0) { cout<< " you are " <<age<<" years old" <<endl; }
else if(age==0)
{ Enter your age in years
throw(p); 0
} Exception: Unknown
else if(age<0)
{
throw(3.5f);
}
}
catch(int j)
{ cout<<"Integer Exception, Ex value is:"<<j<<endl;
}
catch(float m) { cout<<"Float Exception, Ex value is: "<<m<<endl; }
catch(char k) { cout<<"Character Exception, Ex value is: "<<k; }
catch(...) { cout << "Exception: Unknown"; }
}
Exceptions
Analysis of Exception Handling

Comparison of exception handling with


traditional error handling.

1) Separation of Error Handling code from Normal


Code:
In traditional error handling codes, there are
always if else conditions to handle errors. These
conditions and the code to handle errors get mixed
up with the normal flow. This makes the code less
readable and maintainable. With try catch blocks,
the code for error handling becomes separate from
the normal flow.
Exceptions
Analysis of Exception Handling

2) Functions/Methods can handle any exceptions


they choose:
A function can throw many exceptions, but
may choose to handle some of them. The other
exceptions which are thrown, but not caught can be
handled by caller.

In C++, a function can specify the exceptions


that it throws using the throw keyword. The
caller of this function must handle the exception
in some way (either by specifying it again or
catching it)
Exceptions
Analysis of Exception Handling

3) Grouping of Error Types:

In C++, both basic types and objects can be


thrown as exception. We can create a hierarchy
of exception objects, group exceptions in
namespaces or classes, categorize them
according to types.
Exceptions
Analysis of Exception Handling

4) Programmers can deal with them at


some level within the program. If an
error can't be dealt with at one level, then
it will automatically be shown at the
next level, where it can be dealt with.
Exceptions
Analysis of Exception Handling

5) The extra overhead associated with the


C++ exception handling mechanism
may increase the size of executable files
and slow your program execution.
Exceptions
Analysis of Exception Handling

To avoid exceptions overheads, it should be used only in


truly exceptional situations. Exception handlers should
not be used to redirect the program's normal flow of
control.
For example, an exception should not be thrown in
cases of potential logic or user input errors, such as the
overflow of an array boundary. In these cases, simply
returning an error code by using for example, the
conditional if statement may be simpler and more
concise.
Exceptions
Why we need to use exceptions

• When a program crashes, inform the user


and exit gracefully.
• Inform the user and allow the user to try
to recover and continue.
• Take corrective action and continue
without disturbing the user.
Exceptions
C++ Standard Exceptions

C++ provides a number of standard exceptions


which are defined in <exception> and can be
used in our programs.
Exceptions

class hierarchy

Source: https://www.tutorialspoint.com/
Exceptions
Exception & Description

1 std::exception
An exception and parent class of all the standard C++ exceptions.
2 std::bad_alloc
This can be thrown by new.
3 std::bad_cast
This can be thrown by dynamic_cast.
4 std::bad_exception
This is useful device to handle unexpected exceptions in a C++
program.

5 std::bad_typeid
This can be thrown by typeid.
6 std::logic_error
An exception that theoretically can be detected by reading the code.
7 std::domain_error
This is an exception thrown when a mathematically invalid domain is
used.
8 std::invalid_argument
This is thrown due to invalid arguments.
Exceptions

9 std::length_error
This is thrown when a too big std::string is created.
10 std::out_of_range
This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().
11 std::runtime_error
An exception that theoretically cannot be detected by reading the code.
12 std::overflow_error
This is thrown if a mathematical overflow occurs.
13 std::range_error
This is occurred when you try to store a value which is out of range.
14 std::underflow_error
This is thrown if a mathematical underflow occurs.

Source: https://www.tutorialspoint.com/

You might also like