SlideShare a Scribd company logo
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

PPTX
Lecture 3.1.1 Try Throw Catch.pptx
PPT
Exception handling
PPTX
Java Exceptions and Exception Handling
PPTX
6-Error Handling.pptx
PPTX
Lecture 20-21
PPT
F6dc1 session6 c++
PPTX
Exceptions overview
PDF
Design byexceptions
Lecture 3.1.1 Try Throw Catch.pptx
Exception handling
Java Exceptions and Exception Handling
6-Error Handling.pptx
Lecture 20-21
F6dc1 session6 c++
Exceptions overview
Design byexceptions

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

PDF
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
PPT
Exception
PDF
PDF
PPSX
Exception hierarchy
PPT
Exception Handling Exception Handling Exception Handling
PPTX
JAVA Presenttation topics Programs.pptx
PPTX
Exception Handling in UiPath.pptx
PPTX
PPTX
Exception handling
PPTX
Module 4-packages and exceptions in java.pptx
PPT
Exception handling
PPTX
Exception handling in ASP .NET
PPT
9781285852744 ppt ch14
PPT
Md07 exceptions&assertion
PPT
Exception and Error Handling in C++ - A detailed Presentation
PPTX
Exception handling
PPTX
Debugging
PPT
UNIT III.ppt
PPT
UNIT III (2).ppt
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
Exception
Exception hierarchy
Exception Handling Exception Handling Exception Handling
JAVA Presenttation topics Programs.pptx
Exception Handling in UiPath.pptx
Exception handling
Module 4-packages and exceptions in java.pptx
Exception handling
Exception handling in ASP .NET
9781285852744 ppt ch14
Md07 exceptions&assertion
Exception and Error Handling in C++ - A detailed Presentation
Exception handling
Debugging
UNIT III.ppt
UNIT III (2).ppt
Ad

Recently uploaded (20)

PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Welding lecture in detail for understanding
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
Structs to JSON How Go Powers REST APIs.pdf
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
UNIT 4 Total Quality Management .pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Sustainable Sites - Green Building Construction
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
OOP with Java - Java Introduction (Basics)
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
Foundation to blockchain - A guide to Blockchain Tech
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Welding lecture in detail for understanding
CH1 Production IntroductoryConcepts.pptx
additive manufacturing of ss316l using mig welding
Internet of Things (IOT) - A guide to understanding
Structs to JSON How Go Powers REST APIs.pdf
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
UNIT 4 Total Quality Management .pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
CYBER-CRIMES AND SECURITY A guide to understanding
Sustainable Sites - Green Building Construction
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
OOP with Java - Java Introduction (Basics)
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Model Code of Practice - Construction Work - 21102022 .pdf
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Lesson 3_Tessellation.pptx finite Mathematics
Foundation to blockchain - A guide to Blockchain Tech
Ad

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

  • #6: 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