Presentation is loading. Please wait.

Presentation is loading. Please wait.

Throwing and catching exceptions

Similar presentations


Presentation on theme: "Throwing and catching exceptions"— Presentation transcript:

1 Throwing and catching exceptions

2 Outline In this lesson, we will:
Learn that not all exceptions can be dealt with locally See that we can throw exceptions These thrown exceptions either terminate the program, or Be caught by a previous calling function The handling of the exception

3 Introduction Up to this point, functions returned values
The caller could be notified that an exceptional situation occurred by one of the following: Returning a specific value Passing a flag by reference Passing back a structure

4 Identifying exceptions
Returning specific values: int main(); Returns 0 if all is okay, and any other number generally signals an issue Passing a flag by reference: int add( int a, int b, bool &is_valid ); If a + b causes an underflow or overflow, is_valid is assigned false and the returned value is ignored, Otherwise, is_valid is assigned true and the returned value is the product

5 Identifying exceptions
Returning a structure: struct return_t { int value; bool is_valid; }; return_t add( int a, int b ); If a + b causes an underflow or overflow, is_valid is assigned false and the value member variable is ignored, Otherwise, is_valid is assigned true and the product is assigned to value

6 Identifying exceptions
Situation: Suppose you establish an Internet socket connection Your program is communicating with another program on a remote computer In the midst of this communication, a function called a function which called yet another function which tries to send data to the other program via the socket Problem: The socket connection failed—the other computer was shut down

7 Identifying exceptions
Each function declaration would require a flag: typename function#( parameters…, bool &socket_fail ); The argument passed by reference could be continually passed down and if it ever set to true, just return—it will still be set to true typename function1( parameters…, bool &socket_fail ) { // Do something... data = function2( arguments…, socket_fail ); if ( socket_fail ) { return default_value; } // Do something else...

8 Identifying exceptions
Instead, what we really want is: typename top_level_function( parameters… ) { // Establish a socket connection... bool finished{false}; while ( !finished ) { // Communicate with the other computer if ( any-problem-occurred-with-the-connection ) { // Re-establish the connection... } else { finished = true; }

9 Identifying exceptions
This becomes more difficult as systems become more and more complex while the number of possible exceptions that must be identified increases Additionally, suppose that you need to pass back information regarding the failure What type of failure? What were the circumstances? What was the state? Was there a partial transmission of information?

10 Throwing exceptions The try-throw-catch mechanism allows functions to call other functions, and if all is good, you get a return value…no problem If an exceptional circumstance occurs, we can throw an exception int add( int m, int n ) { int result = m + n; if ( ((m > 0) && (n > 0) && (result <= 0)) || ((m < 0) && (n < 0) && (result >= 0)) ) { throw 0; // The value can be any literal or // other instance of any type } return result;

11 Throwing exceptions Suppose we call this function: Output int main() {
std::cout << "Answer: “ << add( , 1 ) << std::endl; std::cout << "Answer: " << add( , 1 ) return 0; } Output Answer: terminate called after throwing an instance of 'int' Aborted (core dumped)

12 Throwing exceptions The exception thrown terminated the program
It indicated the type of the object thrown std::cout << "Answer: " << add( , 1 ) << std::endl; Nothing was printed—the exception immediately terminated the program

13 Throwing exceptions Problem: Result? Where possible, we’d like to:
You are a software designer for a program like Microsoft Word If you throw an exception anywhere, the program terminates Result? Millions of disaffected users… Where possible, we’d like to: Catch the thrown exception, and Handle the exception That is, deal with it… Sky Sports: Ashes Live

14 Catching exceptions The solution is to actually catch the exception:
try { // Execute some code that may throw an exception... // - if no exception is ever thrown, all is well } catch ( ... ) { // Handle the exception: // Execute this code only if an exception is thrown // - as soon any exception is thrown in the // above code, continue executing this statement // block } // In either case, continue // execution here

15 Catching exceptions For example: int main() { try {
std::cout << add( , 1 ) << std::endl; } catch( ... ) { std::cout << "An exception was thrown..." << std::endl; } std::cout << "Finished first try-catch block..." << std::endl; std::cout << add( , 1 ) << std::endl; std::cout << "Finished second try-catch block..." << std::endl; return 0;

16 Catching exceptions The output and flow chart are: Output: 2147483647
Finished first try-catch block... An exception was thrown... Finished second try-catch block...

17 Catching exceptions Important:
Everything up to the exception being thrown is executed int main() { try { std::cout << add( , 1 ) << std::endl; std::cout << add( , 2 ) << std::endl; std::cout << add( , 3 ) << std::endl; std::cout << add( , 4 ) << std::endl; std::cout << add( , 5 ) << std::endl; } catch( ... ) { std::cout << "An exception was thrown..." << std::endl; } return 0; Output: An exception was thrown...

18 Catching exceptions The flow chart and the output are Output:
An exception was thrown...

19 Catching exceptions As a second example:
The for-loop continues execution until an exception is thrown int main() { try { for ( int k{0}; k > 10; --k ) { std::cout << add( , k ) << std::endl; } } catch( ... ) { std::cout << "An exception was thrown..." << std::endl; return 0; Output: An exception was thrown...

20 Catching exceptions Now, a function can return a value
Can an exception return a value we can use? Suppose we want to return the invalid result when adding two integers: int add( int m, int n ) { int result = m + n; if ( ((m > 0) && (n > 0) && (result <= 0)) || ((m < 0) && (n < 0) && (result >= 0)) ) { throw result; } return result;

21 Catching exceptions As you may guess, we can replace ... with something try { // Execute some code that may throw an exception... // - if no exception is ever thrown, all is well } catch ( typename identifier ) { // Execute this code only if the value thrown was of // the type 'typename' // - the value thrown is assigned to 'identifier' } // In either case, continue execution here // - If the type was different, // continue throwing higher

22 Catching exceptions Here is the flow chart:
If the exception thrown was not of the given type: It is described as an uncaught exception It continues to be thrown higher If it is not caught at some point, the program will terminate

23 Catching exceptions Alternatively, you can still catch all other exceptions: try { // Execute some code that may throw an exception... } catch ( typename identifier ) { // Execute this code only if the value thrown was of // the type 'typename' // - the value thrown is assigned to 'identifier' } catch ( ... ) { // Execute this code if something not of 'typename' // was thrown } // In all cases, continue execution here

24 Catching exceptions Here is the flow chart: try {
// Execute some code that may throw an exception... } catch ( typename identifier ) { // Execute this code only if the value thrown was of // the type 'typename' // - the value thrown is assigned to 'identifier' } catch ( ... ) { // Execute this code if something not of 'typename' // was thrown } // In all cases, // continue execution here

25 Catching exceptions You can even have multiple catch statements: try {
// Execute some code that may throw an exception... // - if no exception is ever thrown, all is well } catch ( typename_1 identifier_1 ) { std::cout << "A 'typename_1' exception thrown:" << identifier_1 << std::endl; } catch ( typename_2 identifier_2 ) { std::cout << "A 'typename_2' exception thrown:" << identifier_2 << std::endl; } catch ( typename_3 identifier_3 ) { std::cout << "A 'typename_3' exception thrown:" << identifier_3 << std::endl; } catch ( ... ) { std::cout << "An exception of an unknown type was thrown" << std::endl; } // In any case, continue execution here

26 Catching exceptions Here are the flow charts:
With a catch( ... ) statement: Without it:

27 Catching exceptions Using try-catch statement as a goto in disguise is possible but discouraged: try { // Do something... if ( some-condition ) { throw 0; } // Continue doing something... } catch ( ... ) { // Essentially a 'goto here' and do // something else...

28 Re-throwing exceptions
Catching exceptions is also referred to as exception handling Finally, if when catching an exception, you realize that the exception cannot be handled, you can always re-throw the exception: try { // Do something... // Continue doing something... } catch ( ... ) { // Try handling the exception throw value; }

29 Using try-catch The try-catch statement is generally only used in larger general-purpose applications There is a significant overhead incurred to allow a program to jump down the call stack It generally is not used in embedded real-time systems

30 Identifying exceptions
Going back to our original example: typename top_level_function( parameters… ) { // Establish a socket connection... bool finished{false}; while ( !finished ) { try { // Communicate with the other computer // - functions call other functions which call others // - at any time, the connection may be lost // We only get here if no exception is thrown finished = true; } catch( ... ) { // Re-establish the connection... }

31 Summary Following this lesson, you now:
Know that some exceptions cannot be dealt with locally For such exceptions, you can throw an exception Understand that exceptions will either Cause the program to terminate, or Be caught by a calling routine Understand the mechanism for catching exceptions Know how to: Catch an arbitrary exception, or Catch an exception based on type of that being thrown

32 References [1] No references?

33 Colophon These slides were prepared using the Georgia typeface. Mathematical equations use Times New Roman, and source code is presented using Consolas. The photographs of lilacs in bloom appearing on the title slide and accenting the top of each other slide were taken at the Royal Botanical Gardens on May 27, 2018 by Douglas Wilhelm Harder. Please see for more information.

34 Disclaimer These slides are provided for the ece 150 Fundamentals of Programming course taught at the University of Waterloo. The material in it reflects the authors’ best judgment in light of the information available to them at the time of preparation. Any reliance on these course slides by any party for any other purpose are the responsibility of such parties. The authors accept no responsibility for damages, if any, suffered by any party as a result of decisions made or actions based on these course slides for any other purpose than that for which it was intended.


Download ppt "Throwing and catching exceptions"

Similar presentations


Ads by Google