SlideShare a Scribd company logo
1 of 26
DISCOVER . LEARN . EMPOWER
Topic: Try, Throw, Catch
INSTITUTE - UIE
DEPARTMENT- ACADEMIC UNIT-2
Bachelor of Engineering (Computer Science & Engineering)
Subject Name: Object Oriented Programming using C++
Code:20CST151
Unit-3
Object Oriented
Programming
using C++
Course Objectives
2
• 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.
3
CO
Number
Title Level
CO1 Provide the environment that allows students to
understand object-oriented programming Concepts.
Understand
CO2 Demonstrate basic experimental skills for differentiating
between object-oriented and procedural programming
paradigms and the advantages of object-oriented
programs.
Remember
CO3 Demonstrate their coding skill on complex programming
concepts and use it for generating solutions for
engineering and mathematical problems.
Understand
CO4 Develop skills to understand the application of classes,
objects, constructors, destructors, inheritance, operator
overloading and polymorphism, pointers, virtual
functions, exception handling, file operations and
handling.
Understand
Course Outcomes
Scheme of Evaluation
4
Sr.
No.
Type of Assessment
Task
Weightage of actual
conduct
Frequency of Task Final Weightage in Internal
Assessment (Prorated
Marks)
Remarks
1. Assignment* 10 marks of
each assignment
One Per Unit 10 marks As applicable to
course types depicted
above.
2. Time Bound
Surprise
Test
12 marks for each
test
One per Unit 4 marks As applicable to
course types
depicted above.
3. Quiz 4 marks of each quiz 2 per Unit 4marks As applicable to
course types
depicted above.
4. Mid-Semester Test** 20 marks for one
MST.
2 per semester 20 marks As applicable to
course types
depicted above.
5. Presentation*** Non Graded: Engagement
Task
Only for Self Study
MNGCourses.
6. Homework NA One per lecture topic
(of 2
questions)
Non-Graded: Engagement
Task
As applicable to
course types
depicted above.
7. Discussion Forum NA One per
Chapter
Non Graded: Engagement
Task
As applicable to
course types depicted
above.
8. Attendance and
Engagement Score
on BB
NA NA 2 marks
• What is an Exception
• Exception Handler Try, Throw,
Catch
5
CONTENTS
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
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.
7
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.
8
EXCEPTION HANDLING
9
Figure 1: Syntax
• 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”.
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.
10
Exception Handling Mechanism
• Error handling code basically consists of two parts.
Detect error and throw the exception (in try block)
Catch exception and take appropriate action. (in catch block)
• Steps to be followed are:
1. Find the problem (Hit the exception).
2. Inform that error has occurred (throw the exception).
3. Receive the error information (catch the exception).
4. Take corrective actions (handle the exception).
11
Exception Handling Mechanism
• Exception handling basically has 3 keywords:
1. Try
2. Throw
3. Catch
• 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.
12
Exception Handling Mechanism
13
Figure 2: Depiction of try catch block
26-09-2022
• 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.
4
Throw and Catch
26-09-2022
• 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.
5
Throw and Catch
26-09-2022 5
Throw and Catch
try
{ // code
if ( x )
throw 10;
// code
if (y)
throw 20;
//code
}
try { // code here }
catch (int param) {
cout << "int exception";
}
catch (char param) {
cout << "char exception";
}
catch (...) {
cout << "default exception";
}
17
26-09-2022 6
Throwing an Exception in a Function
19
Applications
• Helps in finding and handling run-time anomalies or abnormal
conditions that a program encounters during its execution.
20
21
Summary
In this lecture we have
discussed about Exception
Handling.
We have discussed some
examples of try throw catch
blocks
Moreover, we have learnt
about how to use exception
handling in functions
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).
22
Assessment Questions:
23
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
2. Why do we need to handle exceptions?
a) To avoid unexpected behaviour of a program during run-time
b) To let compiler remove all exceptions by itself
c) To successfully compile the program
d) To get correct output
3. How Exception handling is implemented in the C++ program?
a) Using Exception keyword
b) Using try-catch block
c) Using Exception block
d) Using Error handling schedules
Discussion forum.
What are the various C++ Standard Exceptions?
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-exception-handling-1/
2. https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
3. https://www.geeksforgeeks.org/exception-handling-c/
25
THANK YOU

More Related Content

Similar to Lecture 1 Try Throw Catch.pptx (20)

CS3391 -OOP -UNIT – III NOTES FINAL.pdf
CS3391 -OOP -UNIT – III  NOTES FINAL.pdfCS3391 -OOP -UNIT – III  NOTES FINAL.pdf
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
 
Exception
ExceptionException
Exception
 
$Cash
$Cash$Cash
$Cash
 
$Cash
$Cash$Cash
$Cash
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 
Exception Handling in UiPath.pptx
Exception Handling in UiPath.pptxException Handling in UiPath.pptx
Exception Handling in UiPath.pptx
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
9781285852744 ppt ch14
9781285852744 ppt ch149781285852744 ppt ch14
9781285852744 ppt ch14
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception handling
Exception handlingException handling
Exception handling
 
Debugging
DebuggingDebugging
Debugging
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Unit iii pds
Unit iii pdsUnit iii pds
Unit iii pds
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 

Recently uploaded

Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 

Recently uploaded (20)

Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 

Lecture 1 Try Throw Catch.pptx

  • 1. DISCOVER . LEARN . EMPOWER Topic: Try, Throw, Catch INSTITUTE - UIE DEPARTMENT- ACADEMIC UNIT-2 Bachelor of Engineering (Computer Science & Engineering) Subject Name: Object Oriented Programming using C++ Code:20CST151 Unit-3
  • 2. Object Oriented Programming using C++ Course Objectives 2 • 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.
  • 3. 3 CO Number Title Level CO1 Provide the environment that allows students to understand object-oriented programming Concepts. Understand CO2 Demonstrate basic experimental skills for differentiating between object-oriented and procedural programming paradigms and the advantages of object-oriented programs. Remember CO3 Demonstrate their coding skill on complex programming concepts and use it for generating solutions for engineering and mathematical problems. Understand CO4 Develop skills to understand the application of classes, objects, constructors, destructors, inheritance, operator overloading and polymorphism, pointers, virtual functions, exception handling, file operations and handling. Understand Course Outcomes
  • 4. Scheme of Evaluation 4 Sr. No. Type of Assessment Task Weightage of actual conduct Frequency of Task Final Weightage in Internal Assessment (Prorated Marks) Remarks 1. Assignment* 10 marks of each assignment One Per Unit 10 marks As applicable to course types depicted above. 2. Time Bound Surprise Test 12 marks for each test One per Unit 4 marks As applicable to course types depicted above. 3. Quiz 4 marks of each quiz 2 per Unit 4marks As applicable to course types depicted above. 4. Mid-Semester Test** 20 marks for one MST. 2 per semester 20 marks As applicable to course types depicted above. 5. Presentation*** Non Graded: Engagement Task Only for Self Study MNGCourses. 6. Homework NA One per lecture topic (of 2 questions) Non-Graded: Engagement Task As applicable to course types depicted above. 7. Discussion Forum NA One per Chapter Non Graded: Engagement Task As applicable to course types depicted above. 8. Attendance and Engagement Score on BB NA NA 2 marks
  • 5. • What is an Exception • Exception Handler Try, Throw, Catch 5 CONTENTS
  • 6. 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
  • 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. 7
  • 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. 8
  • 9. EXCEPTION HANDLING 9 Figure 1: Syntax • 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”.
  • 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. 10
  • 11. Exception Handling Mechanism • Error handling code basically consists of two parts. Detect error and throw the exception (in try block) Catch exception and take appropriate action. (in catch block) • Steps to be followed are: 1. Find the problem (Hit the exception). 2. Inform that error has occurred (throw the exception). 3. Receive the error information (catch the exception). 4. Take corrective actions (handle the exception). 11
  • 12. Exception Handling Mechanism • Exception handling basically has 3 keywords: 1. Try 2. Throw 3. Catch • 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. 12
  • 13. Exception Handling Mechanism 13 Figure 2: Depiction of try catch block
  • 14. 26-09-2022 • 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. 4 Throw and Catch
  • 15. 26-09-2022 • 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. 5 Throw and Catch
  • 16. 26-09-2022 5 Throw and Catch try { // code if ( x ) throw 10; // code if (y) throw 20; //code } try { // code here } catch (int param) { cout << "int exception"; } catch (char param) { cout << "char exception"; } catch (...) { cout << "default exception"; }
  • 17. 17
  • 18. 26-09-2022 6 Throwing an Exception in a Function
  • 19. 19
  • 20. Applications • Helps in finding and handling run-time anomalies or abnormal conditions that a program encounters during its execution. 20
  • 21. 21 Summary In this lecture we have discussed about Exception Handling. We have discussed some examples of try throw catch blocks Moreover, we have learnt about how to use exception handling in functions
  • 22. 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). 22
  • 23. Assessment Questions: 23 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 2. Why do we need to handle exceptions? a) To avoid unexpected behaviour of a program during run-time b) To let compiler remove all exceptions by itself c) To successfully compile the program d) To get correct output 3. How Exception handling is implemented in the C++ program? a) Using Exception keyword b) Using try-catch block c) Using Exception block d) Using Error handling schedules
  • 24. Discussion forum. What are the various C++ Standard Exceptions? 24
  • 25. 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 3. https://www.geeksforgeeks.org/exception-handling-c/ 25

Editor's Notes

  1. Computer in the diagram is 3rd generation computer. The period of third generation was from 1965-1971. The computers of third generation used Integrated Circuits (ICs) in place of transistors. A single IC has many transistors, resistors, and capacitors along with the associated circuitry. The main features of third generation are − IC used More reliable in comparison to previous two generations Smaller size Generated less heat Faster Lesser maintenance Costly AC required Consumed lesser electricity Supported high-level language