Cse232 Exceptions and String Stream
Cse232 Exceptions and String Stream
Assert
▪ If it is not true, then we halt the program and report the problem
▪ The string always represents a true value (Boolean). If the first value becomes false,
then the assert triggers and the message at halt contains your string.
Example 11.1
Why is this a mistake?
assert(in_file.is_open() || “failed file open”)
▪ Keywords
▪ try: a block where code is run and if an error occurs an exception is thrown,
potentially to catch with other code
▪ throw: raises an exception
▪ catch: a block where an exception is caught and handled (in conjunction with try)
Non-local control
▪ Basic idea:
▪ Keep watch on a particular section of code
▪ If we get an exception raise / throw that exception (let it be known)
▪ Look for a catcher that can handle that kind of exception
▪ If catcher found, catcher handles the error.
▪ Otherwise, end the program
#include<stdexcept>
try {
code to run
} catch (type err_instance) {
stuff to do on error
}
Which keyword is used to create an exception?
● raise
● except
● throw
● I don't know
Try block
▪ The try block contains code that we want to keep an eye on, to watch and
see if any kind of errors occur
▪ If no exception in the try block, skip past all the catch blocks to the following
code
▪ If an error occurs in a try block, look for the right catch by type
● Yes
● No
● In C++, yes, in Python, no.
● I don't know
throw
▪ Can look at the docs to determine what exceptions an operation can throw
Example 11.3
stod, stol
▪ Input
▪ Output
#include<sstream>
string word;
char ch;
istringstream iss(“hello world”);
iss >> word; // space sep, “hello”
iss.get(ch); // the space
iss.get(ch); // ‘w’
Example 11.6
ostringstream
▪ This allows you to output using all the cout operators, then turn it into one string at the end
▪ Thus you can get rounding, widths, etc., just as you would with cout
Example
ostringstream oss;
oss << fixed << setprecision(4) << boolalpha;
oss << 3.14159 << “ is great == “ << true << endl;
cout << oss.str();
Output: 3.1416 is great == true
Example 11.7
So, why?
▪ istringstream:
▪ cin is tricky. Get the whole line and use stream ops to parse the line via an
istringstream.
▪ ostringstream:
▪ Write, using all the type info and stream ops into a string, then you can further
manipulate
How can you convert a string to a long?
● Using stol
● Using istringstream
● Looping over the chars in the
string
● I don't know