Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Exceptions.

Similar presentations


Presentation on theme: "C++ Exceptions."— Presentation transcript:

1 C++ Exceptions

2 Exceptions Exceptions are run-time anomalies
E.g. running out of memory E.g. Bad input (alpha where numeric is expected) In well-designed programs exceptions are a subset of program’s error handling

3 C Program Error Handling
Main() calls: A() and A calls: B() and B calls: C(). Error occurs in C(). How do we let caller main() know that error occured.?? Only way is to return a code which is: Checked by B() and then returned to A(): Code is then checked by A() and returned to main(). Global return code variable is also possible but ugly 

4 … C Program Error Handling
Code will be littered with if checks: if (rc = A()) != 0) then return rc; if (rc = B()) != 0) then return rc; if (rc = C() != 0) then return rc; Reduces code readability Requires standardization of return code across all functions in the chain and actually the entire program. Too painful 

5 Exceptions to the rescue
Part of a program encounters a problem (like C()). It needs a way to transfer control to that part of the program that can handle the problem Further information about the problem also needs to be communicated C++ Exceptions provide this capability All OOPL (C#, Java) have Exceptions.

6 throw The error detecting part of the program can ‘throw’ an exception. We also say that it raised an exception To pass information about the error (exception) an exception object can be passed by the ‘throwing’ code

7 … throw The exception object is an instance of any of a set of exception classes defined by the (standard) library or new exception classes created by the user. throw runtime_error(“Data must refer to same isbn”); runtime_error is a standard exception class (type).

8 try-catch The error-handling part of the code uses a try block followed by (one or more) catch clause(s) try { Program-statements … } catch (exception err) { Catch-handler-statements … }

9 … try-catch Exceptions thrown by Program-statements in try block are caught by the (matching) catch clause/handler. The throw statement can be deep within a function call chain invoked by a program statement in the try block. The exception thrown in a nested function chain (say in C())

10 … try-catch Travels up the function call chain one-by-one checking for a try-catch statement (with an appropriate handler) If not found (like in case of B()) it will go further up the chain and so on until a try-catch handler is found In our case the try-catch could be in main() and so that catch handler’s statements will be executed.

11 … try-catch After the catch handler finishes the first statement following the last catch clause is executed.

12 ModExceptionExample.cpp See ModExceptionExample.cpp
throw and catch both use runtime_error exception class throw statement creates the exception object (runtime_error) giving it constructor arguments (error message). what() method of all exception classes give the error message. This what() method is used by catch handler to display error message set up by throw in the exception object.

13 What if there is no try-catch?
Let’s say we have throw in C() But no try-catch anywhere. Then what happens if C() throws an exception (raises an exception)?

14 … What if there is no try-catch?
C++ runtime environment catches it and the program is terminated. So if any functions, object methods() used by main or other program functions throw an exception they must be caught or else program crashes!!!! Standard C++ library functions do not use exceptions heavily. So we have managed to write a lot of code without exception handling

15 Java, C# Exception Usage
But in some cases in C++ we need it (as we will see shortly). In Java and C#, in contrast, exceptions are used left, right and centre. For example, equivalent of cin to read an integer, in Java or C#, will raise an exception if alphabetic (or other invalid) data is specified!!

16 Java, C# Exception Usage
So if you do not have a try-catch for even a simple cin like statement to accept a number your program can be crashed by the user!! You may be using C# or Java in future. So it is important to learn exceptions well now.

17 Exception class hierarchy
exception class is the base class of all standard C++ exceptions runtime_error exception derives from exception catch handler for exception object can handle all derived objects like runtime_error. See except2.cpp

18 Multiple catch handlers
Multiple catch handlers are written in order of derived class to base class. When an exception is caught in a try block the catch clauses/handlers are examined in the order in which they are written. The first catch clause with a type matching the thrown exception is invoked.

19 Multiple catch handlers
Other catch clauses are then ignored. See except3.cpp and except4.cpp

20 Functions Exited During Search for a Handler
When an exception is thrown a search for a matching handler is made up the call chain. During this process if no matching handler is found at a function level then that function is terminated and the search continues from its caller function E.g. If C() throws the exception, there is no matching try-catch() in C() itself so C() will be exited (terminated) first. [Its stack data (automatic variables) will be freed.]

21 … Functions Exited During Search for a Handler
Then as B() does not have a handler, B() will be exited (terminated). Then as A() does not have a handler A() will be exited (terminated). Finally main() has a matching handler and its catch handler code will be executed This process is also called ‘Stack unwinding’

22 Multiple try-catch In real-life (complex) programs you will have multiple try-catch statements. E.g. you could have a try-catch in main(), A() and B(). In such cases it is possible that the nearest try-catch in the call chain does not have a matching handler. So then that try-catch will be ignored and the search for a handler will continue up the call chain till a matching handler is encountered

23 Book Section for try-catch
Section 6.13 (page 215 to page 220)

24 Assignment 9A Write a program that finds out the maximum memory that can be allocated on the heap using new. The figure should be reported in MB (rounded down). Hint 1: See point 3 of Standard Exceptions (in course book). Hint 2: Allocate a character array of 1 MB using new, in an infinite loop.

25 Book Source Code Copyright Note
The course book is C++ Primer, 4th Edition by Lippman, Lajoie and Moo. Any references in earlier files to source files, and use of code within those files, are of example code given in and/or along with the book. As these slides are freely accessible on the Internet, not-for-profit, and for educational purposes, based on the permission related statements in the source code, I have considered that permission has been granted to use them in these slides.


Download ppt "C++ Exceptions."

Similar presentations


Ads by Google