Throwing exceptions.

Slides:



Advertisements
Similar presentations
Throwing and catching exceptions
Advertisements

Recursive binary search
For loops.
Templates.
Introduction to classes
Static variables.
Default values of parameters
Pointers.
Dynamically allocating arrays
Anatomy of a program.
Switch statement.
Do-while loops.
Command-line arguments
Throwing exceptions.
Pointer arithmetic.
Console input.
Dangling pointers.
Hello world!.
This.
Sorted arrays.
Dynamically allocating arrays within structures
Break statements.
Wild pointers.
Console output.
The comma as a separator and as an operator
Selection sort.
Bucket sort.
The ternary conditional operator
Throwing exceptions.
Dynamically allocating structures
Bit-wise and bit-shift operators
Sorting algorithms.
Command-line arguments
Passing pointers as parameters to and from functions
Templated Linked Lists
Polymorphism.
Dynamically allocating arrays
Problems with pointers
Protecting pointers.
Dynamically allocating arrays
Code-development strategies
Anatomy of a program.
Console output.
Selection sort.
Pointers as arguments and return values
Reference variables, pass-by-reference and return-by-reference
Addresses and pointers
Default values of parameters
Pointer arithmetic.
Recursive functions.
Class variables and class functions
Operator overloading.
The std::string class.
Dynamic allocation of arrays
Templates.
Sorted arrays.
Sorting algorithms.
Issues with classes.
Dangling pointers.
Dynamic allocation of classes
Encapsulation.
Destructors.
Counting sort.
Selection sort.
Searching and sorting arrays
Protecting pointers.
Data structures: class
An array class: constructor and destructor
Constructors.
Recursive binary search
Presentation transcript:

Throwing exceptions

Outline In this lesson, we will: Describe the concept of throwing exceptions Introduce exception classes and the stdexcept library A common constructor and a public member function what() Look at examples of throwing exceptions

Constructors Suppose something goes wrong We can throw an exception that raises The Standard Template Library (stl) defines a number of exception classes, all of which have a similar interface: The constructor takes a string as an argument A public member function what() returns that string as a character array

Thrown exceptions The default behavior for thrown exceptions is program termination: Here, the array length is invalid: #include <iostream> int main(); int main() { int n{-10}; int *a_data = new int[n]; delete[] a_data; return 0; } terminate called after throwing an instance of 'std::bad_array_new_length' what(): std::bad_array_new_length Abort (core dumped)

Standard exceptions The library stdexcept defines nine standard exceptions These are related to design issues: Class Description Example logic_error An issue that should have been dealt with in development The conditions are not met for calling a function domain_error A function is being called with an invalid argument Calling a logarithm on a negative number invalid_argument A more general domain error An invalid uWaterloo Student ID number length_error An invalid length an array Making an array holding a string shorter than the string out_of_range An array or string index is invalid Accessing a character beyond the end of a string You don’t have to memorize these – for informational purposes only

Standard exceptions The library stdexcept defines nine standard exceptions These are related to run-time issues: Class Description Example runtime_error An issue that can only be detected during execution The conditions are not met for calling a function range_error The result of a function is not representable Calling a logarithm on a negative number overflow_error An arithmetic operation results in an overflow Adding two ints with a result greater than or equal to 231 underflow_error An arithmetic operation results in an underflow Taking the difference between two unsigned int with the result being negative You don’t have to memorize these – for informational purposes only

Thrown exceptions By definition, the argument of a factorial cannot be negative, but not all factorials can be represented by int #include <stdexcept> int factorial( int n ) { if ( n < 0 ) { throw std::domain_error( "Cannot calculate n! for n < 0." ); } else if ( n <= 12 ) { int result{1}; for ( int k{1}; k <= n; ++k ) { result *= k; } return result; } else { // This could also be a range error throw std::overflow_error( "n! cannot be represented as an 'int'." );

Thrown exceptions For example, if we execute the following code: #include <stdexcept> #include <iostream> // Function declarations int main(); int factorial( int n ); int main() { std::cout << factorial( 10 ) << std::endl; std::cout << factorial( -5 ) << std::endl; std::cout << factorial( 99 ) << std::endl; std::cout << "Finished execution." << std::endl; return 0; } Output: 3628800 terminate called after throwing an instance of 'std::domain_error' what(): Cannot calculate n! for n < 0. Aborted (core dumped)

Thrown exceptions If we comment out the first error, the second terminates execution #include <stdexcept> #include <iostream> // Function declarations int main(); int factorial( int n ); int main() { std::cout << factorial( 10 ) << std::endl; // std::cout << factorial( -5 ) << std::endl; std::cout << factorial( 99 ) << std::endl; std::cout << "Finished execution." << std::endl; return 0; } Output: 3628800 terminate called after throwing an instance of 'std::overflow_error' what(): n! cannot be represented as an 'int'. Aborted (core dumped)

Thrown exceptions Our rational number class can also now throw exceptions: Rational Rational::operator*( int n ) { int factor{ gcd( n, denominator_ ) }; n /= factor; if ( (n*numerator_)/n != numerator_ ) { throw overflow_error( "n * a/b is not representable with 'int'" ); } return Rational( n*numerator_, denominator_/factor );

Looking ahead In addition to throwing instances of these classes, we will: See how to catch these exceptions A form of flow control between functions Describe how some of these classes are related through inheritance

Summary Following this lesson, you now Understand the concept of throwing exceptions Are aware of the various classes of exceptions They have a common interface Know how to generate and throw these exceptions

References [1] cplusplus.com http://www.cplusplus.com/reference/stdexcept/

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 https://www.rbg.ca/ for more information.

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.