exceptions handling exceptionally sticky problems
TRANSCRIPT
Proper Response
• Proper response to low level errors depends on high level code– Is this a GUI app?– Unattended server application?
Option 3 - Exceptions
• Exceptions : alternative return mechanism– Way for code to return an error
• Indicate error by throwing a value:– Does not have to match return type
Catching
• …unless you catch it
• try : Try this code… something bad might happen
• catch : Here is how to handle any exceptions– Only run if an exception thrown in try
Catch
• Catch specifies– Type of thing it catches• Only catches that type
– What it will call the thing it caught• Use as variable inside catch
Catch
• Wrong Type == No Catch• Can have multiple catches:
catch(…) • Catches anything - But can't use it as variable
Stack Unwinding
• Thrown exception works back down stack looking for a catch– Does function C catch?– No, how bout B?– No, how bout A?– No, how bout Main?
Std::Excptions
• Std library defines exception class
• exception is parent to all– Has virtual what() function
http://www.cplusplus.com/reference/exception/exception/
Exception Subclasses
• Many subclasses to exception– All support what()– All can be caught as exception
Exception Subclasses
• Can't add information to plain exception:
• Sub classes– Allow for construction with string message– Help specify problem
Reacting to Exceptions
• Choices for dealing with exceptions– Fix the error– Log & Continue– Blow up
• But get to make decision at appropriate level
Announcing a Throw
• Can announce what your function throws:– I throw nothing:
– I thrown exception (or subtypes)
– I throw these two types
What programmers want
• Programmers think this means:
– Announce to other programmers what to expect– Check at compile time that someone will catch– Speed things up by not worrying about other
types
What compiler does
• Compiler does:
– Check at compile time that someone will catchBlow up program at run time if it throws something else
– Speed things up by not worrying about other typesProbably slow things down by doing checks atruntime
What Programmers Need
• Use comments to announce what to expect:
– Announce to other programmers what to expect– Check at compile time that someone will catch– Speed things up by not worrying about other
types