0% found this document useful (0 votes)
2 views

Lecture 3.1.2 3.1.3 Types and Rethrow

The document outlines a course on Object Oriented Programming using C++, focusing on exception handling, including throwing, catching, and rethrowing exceptions. It defines types of exceptions, provides examples of handling them in code, and discusses the importance of exception handling in programming. Additionally, it includes assessment questions and references for further reading.

Uploaded by

Savage King
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)
2 views

Lecture 3.1.2 3.1.3 Types and Rethrow

The document outlines a course on Object Oriented Programming using C++, focusing on exception handling, including throwing, catching, and rethrowing exceptions. It defines types of exceptions, provides examples of handling them in code, and discusses the importance of exception handling in programming. Additionally, it includes assessment questions and references for further reading.

Uploaded by

Savage King
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/ 26

INSTITUTE - UIE

DEPARTMENT- ACADEMIC UNIT-2


Bachelor of Engineering (Computer Science & Engineering)
Subject Name: Object Oriented Programming using C++
Code:22CSH-103

Topic: Throwing an Exception, Catching an


Exception (All types of throw and catch), DISCOVER . LEARN . EMPOWER
Rethrow Exception
Object Oriented
Programming
using C++

Course Objectives

• To enable the students to understand various stages and constructs


of C++ programming language and relate them to engineering
programming problems.
• To improve their ability to analyze and address variety of problems
in programming domains.

2
Course Outcomes
CO Title Level
Number

CO1 Provide the environment that allows students to Understand


understand object-oriented programming Concepts.

CO2 Demonstrate basic experimental skills for differentiating Remember


between object-oriented and procedural programming
paradigms and the advantages of object-oriented
programs.
CO3 Demonstrate their coding skill on complex programming Understand
concepts and use it for generating solutions for
engineering and mathematical problems.

CO4 Develop skills to understand the application of classes, Understand


objects, constructors, destructors, inheritance, operator
overloading and polymorphism, pointers, virtual
functions, exception handling, file operations and
handling.
3
Scheme of Evaluation

4
CONTENTS
• Types of Exceptions
• Throwing an Exception
• Catching an Exception (All types of
throw and catch)
• Rethrow Exception

5
Types of Exceptions

• There are two types of exceptions:


1. Synchronous exceptions
2. Asynchronous exceptions
• Errors such as: out of range index and overflow fall
under the category of synchronous type exceptions.
• Those errors that are caused by events beyond the
control of the program are
called asynchronous exceptions.

6
Throwing Exceptions
• Exceptions can be thrown anywhere within a code block
using throw statement. The operand of the throw statement determines a
type for the exception and can be any expression and the type of the result
of the expression determines the type of exception thrown.
• Following is an example of throwing an exception when dividing by zero
condition occurs −
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

7
Catching Exceptions
• The catch block following the try block catches any exception. You can specify what type of exception you
want to catch and this is determined by the exception declaration that appears in parentheses following the
keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
• Above code will catch an exception of ExceptionName type. If you want to specify that a catch block should
handle any type of exception that is thrown in a try block, you must put an ellipsis, ..., between the
parentheses enclosing the exception declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
8
MULTIPLE CATCH

Figure 6.16 Program made on Dev-C++ 9


MULTIPLE CATCH
• Below program contains multiple catch blocks to handle different types of exception in different way.
#include <iostream>
catch (int ex) // to catch numeric exceptions
#include<conio.h>
{
using namespace std; cout << "Integer exception\n";
int main() }
{ catch (char ex) // to catch character/string exceptions
int x[3] = {-1,2}; {
for(int i=0; i<2; i++) cout << "Character exception\n";
{ }
int ex = x[i]; }
try }
{
if (ex > 0)
// throwing numeric value as exception
throw ex;
else
// throwing a character as exception Output:
throw 'ex'; Integer exception
}
Character exception

• The above program is self-explanatory, if the value of integer in the array x is less than 0, we are throwing a numeric value as exception and if the
value is greater than 0, then we are throwing a character value as exception. And we have two different catch blocks to catch those exceptions.
10
Generalised catch block in C++
• Below program contains a generalized catch block to catch any uncaught errors/exceptions. catch(...) block takes care of all type of
exceptions.

#include <iostream> else


#include<conio.h> throw 'ex';
using namespace std; }
// generalised catch block Output:
int main() catch (...) Special
{ {
int x[3] = {-1,2}; cout << "Special exception\n"; exception
for(int i=0; i<2; i++) } Special
{ } exception
int ex=x[i]; return 0;
try }
{
if (ex > 0)
throw ex;

• In the case above, both the exceptions are being catched by a single catch block. We can even have separate catch blocks to handle
integer and character exception along with the generalised catch block.
11
Re-throwing an Exception
• It’s possible that an exception handler, upon receiving an exception, might decide
either that it cannot process that exception or that it can process the exception only
partially.
• In such cases, the exception handler can defer the exception handling (or perhaps
a portion of it) to another exception handler.
• In either case, you achieve this by re throwing the exception via the statement
throw;
• Regardless of whether a handler can process an exception, the handler can re
throw the exception for further processing outside the handler.

26/05/2025 4
RETHROW EXCEPTION

A function can also re-throw a


function using same “throw; “. A
function can handle a part and can
ask the caller to handle remaining.

Figure 6.21 Rethrow exception [2] 13


Throwing the exception in
Function

14
Throwing the exception in
Function

15
Re-throwing an Exception
#include <iostream>
#include <exception>
using namespace std;
void func1()
{
// throw exception and catch it immediately
try
{
cout << "\n This function throws an exception\n";
throw exception(); //generate exception
} // end try
catch(exception &)
{
cout << " exception is catched in 1st catch block"
<< "\n Function func1 re throws exception";
throw; //rethrow exception for further processing
} // end catch
cout << "This also should not print\n";
} // end of func1
26/05/2025 5
Re-throwing an Exception
int main()
{
try
{
cout << "\n main invokes function func1\n";
func1();
cout << "This should not print\n";
} // end try
catch (exception e) // handle exception
{
cout << "\n\n Exception handled in main\n";
} // end catch
cout << " Program control continues after catch in main\n";
} // end main
26/05/2025 5
Output:

18
Applications
• Helps in finding and handling run-time anomalies or abnormal
conditions that a program encounters during its
execution.

19
Summary

In this lecture we have We have discussed how to


discussed how to throw catch exceptions
exceptions.

Moreover, we have learnt We have also learnt about


about how to rethrow synchronous and asynchronous
exceptions exceptions

20
Frequently Asked question
Q1 Describe the way to handle run time error in C++.
Answer: A runtime error is handled in C++ in the following manner:

- Write the code where the error is predicted after the keyword try.
- Write the solution if a particular exception occurs in the catch block by specifying a parameter which is thrown from the try block.
Or
- Throw the error object by using throw(Exception type object) after try keyword.

1. Describe the way to handle run time error in C++.

2. Explain the exception specification.

Q2 Explain terminate() and unexpected() function.


Answer: - The terminate() is a library function which by default aborts the program.

- It is called whenever the exception handling mechanism cannot find a handler for a thrown exception.

- The unexpected() is called when a function with an exception specification throws an exception of a type that is not listed in the exception
specification for the function

- - A function declaration without a specification like throw(char*) may throw any type of exception, and one with throw() is not allowed to throw
exceptions at all.

- By default unexpected() calls terminate().


21
Assessment Questions:
1. What is the difference between error and exception?
a) Both are the same
b) Errors can be handled at the run-time but the exceptions cannot
c) Exceptions can be handled at the run-time but the errors cannot
d) Both can be handled during run-time

2. What are the different types of exceptions?


a) 1
b) 2
c) 3
d) 4

22
Assessment Questions:
3. Which part of the try-catch block is always fully executed?
a) try part
b) catch part
c) finally part
d) throw part

4. Which of the following is an exception in C++?


a) Divide by zero
b) Semicolon not written
c) Variable not declared
d) An expression is wrongly written

5. What is an error in C++?


a) Violation of syntactic and semantic rules of a languages
b) Missing of Semicolon
c) Missing of double quotes
d) Violation of program interface

23
Discussion forum.
• What are the various synchronous and asynchronous exceptions?
• Examples of various exception handling scenarios.

24
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-exce
ption-handling-1/
2. https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
3. https://www.geeksforgeeks.org/exception-handling-c/ 25
THANK YOU

You might also like