Exception Handling Try Throw Catch (T)
Exception Handling Try Throw Catch (T)
2
Course Outcomes
CO Title Level
Number
3
Scheme of Evaluation
Sr. Type of Assessment Weightage of actual Frequency of Task Final Weightage in Internal Remarks
No. Task conduct Assessment (Prorated
Marks)
5
WHAT IS AN EXCEPTION?
• An exception is a problem that arises during the execution of a
program. A C++ exception is a response to an exceptional
circumstance that arises while a program is running, such as an
attempt to divide by zero.
• Exceptions are different, however. You can't eliminate exceptional
circumstances; you can only prepare for them. Your users will run out
of memory from time to time, and the only question is what you will
do. Your choices are limited to these:
Crash the program.
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.
6
Exception of division example:
Dividing a positive number by zero produces a positive infinity and dividing a negative
number by zero produces a negative infinity.
7
WHAT IS AN EXCEPTION?
• Many kinds of errors can cause exceptions--problems ranging from serious hardware errors, such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds array element.
• When such an error occurs, the method creates an exception object and hands it off to the runtime system.
• The exception object contains information about the exception, including its type and the state of the program when the error occurred.
• The runtime system is then responsible for finding some code to handle the error.
• In programming terminology, creating an exception object and handing it to the runtime system is called throwing an exception.
8
EXCEPTION HANDLER
• After a method throws an exception, the runtime system leaps into action to find someone to handle the exception.
• The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error
occurred.
• The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until
it finds a method that contains an appropriate exception handler.
• An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception
handled by the handler.
• Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods
handles the exception.
• The exception handler chosen is said to catch the exception.
9
EXCEPTION HANDLING
• Errors disrupt normal execution of a program. Exception handling is very necessary, and it is the process of handling errors
or exceptions. It makes sure that the execution of the program is not affected by the exceptions and slowly handles them
without causing any issue to the program execution.
• In C++, exception handling is provided by using three constructs or keywords; namely, try, catch and throw.
• Block of code that provides a way to handle the exception is called “exception handler”.
Figure 1: Syntax
10
Exception Handling Advantages
• It helps the programmer to write robust and fault-tolerant programs that can deal with problems continue executing or
terminate gracefully.
• Exception handling also is useful for processing problems that occur when a program interacts with software elements, such
as member functions, constructors, destructors and classes.
11
Exception Handling Mechanism
12
Exception Handling Mechanism
• In try block, we add those blocks of statements which may generate exceptions. When an
exception is detected, it is thrown using a throw statement in a try block.
• A catch block defined by keyword catch ‘catches’ the exception ‘thrown’ by throw statement
in the try block and handles it appropriately.
• The catch block that catches an exception must immediately follows the try block that throws
the exception.
13
Exception Handling Mechanism
14
Throw and Catch
• The throw statement is almost similar to function call. The only difference is that
instead of calling the function, it calls the catch block.
• In this sense, the catch block is like function definition with a parameter that
matches the type of value being thrown.
• The throw expression accepts one parameter as its argument and this is passed to
the exception handler.
• You can have a number of throw statements at different parts of your try block
with different values being thrown so that the exception handler on receiving the
parameter will know what restorative actions to take.
19/11/2023 4
Throw and Catch
• The exception handler can be identified by the keyword catch .
• catch always takes only one parameter.
• The type of the catch parameter is important as the type of the argument passed by
the throw expression is checked against it and the catch function with the correct
parameter type is executed.
• This way we can chain multiple exception handlers and only the one with the
correct parameter type gets executed.
19/11/2023 5
Exception handling in function:
void sum(float a,float b){
Try
{
if(b==0)
{
cout<<"dividing two numbers\n";
throw b;
} else
{
cout<<"the result after dividing number\n"<<a/b;
}}
catch(float b)
{
cout<<"program is not run due to dividation error"<<endl;
}}
int main() {
sum(5,0); return 0; } 17
Summary
18
Frequently Asked question
Q1 What should I catch?
Answer: In keeping with the C++ tradition of “there’s more than one way to do that” (translation: “give programmers options and tradeoffs so
they can decide what’s best for them in their situation”), C++ allows you a variety of options for catching.
You can catch by value.
You can catch by reference.
You can catch by pointer.
In fact, you have all the flexibility that you have in declaring function parameters, and the rules for whether a particular exception matches (i.e.,
will be caught by) a particular catch clause are almost exactly the same as the rules for parameter compatibility when calling a function.
Q2 What should I throw?
Answer: C++, unlike just about every other language with exceptions, is very accomodating when it comes to what you can throw. In fact, you can
throw anything you like. That begs the question then, what should you throw?
Generally, it’s best to throw objects, not built-ins. If possible, you should throw instances of classes that derive (ultimately) from the std::exception
class. By making your exception class inherit (ultimately) from the standard exception base-class, you are making life easier for your users (they
have the option of catching most things via std::exception), plus you are probably providing them with more information (such as the fact that your
particular exception might be a refinement of std::runtime_error or whatever).
19
Assessment Questions:
1. By default, what a program does when it detects an exception?
a) Continue running
b) Results in the termination of the program
c) Calls other functions of the program
d) Removes the exception and tells the programmer about an exception
20
Discussion forum.
What are the various C++ Standard Exceptions?
21
REFERENCES
TEXT BOOKS
T1 E Balagurusamy., “Object Oriented Programming in C++”, Tata McGraw-Hill.
T2 Robert Lafore, “Object Oriented Programming in C++”, Waite Group.
REFERENCE BOOKS
R1 Herbert Schildt , “C++- The Complete Reference”, Tata McGraw-Hill 2003, New
Delhi.
R2 Bjarne Stroustrup: “The C++ Programming Language” (4th Edition). Addison-
Wesley.
R3 Ravichandran , “Programming with C++”,Tata McGraw-Hill Education.
R4 Joyce M. Farrell,” Object Oriented Programming Using C++”, Learning.
R5 Programming Languages: Design and Implementation (4th Edition), by Terrence W.
Pratt, Marvin V. Zelkowitz, Pearson.
R6 Programming Language Pragmatics, Third Edition, by Michael L. Scott, Morgan
Kaufmann.
Websites:
1. https://www.sanfoundry.com/cplusplus-programming-questions-answers-exception-handling-1
/
2. https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm 22