Tuesday, 15 March 2016

8th March

Exceptions
Exceptions allow you to react to strange behaviour
Throw - throws an exception when a problem shows up
Catch - catches an exception with a handler where you want
Try - helps you identify the code that is wrong and tries something
Ellipsis catch (...) is default handler, like a switch statement default
Try blocks can be nested (try in try in try...) and throwing can pass a try back up
We can use try/catch to stop division by zero so that our program doesn't break (only if we try to catch though)

Look for exception, throw error, handle it.
c++ has many exceptions like bad_alloc built in
But you need to include <exception> to catch them, and you have to use try
We can make our own exceptions by overriding (eg use struct)
When to use - empty disk drive, etc: external issues that we cannot control, so we can send an error message
There is a cost, sometimes dramatic, for using exceptions so use them sparingly
Also don't use for code that has to run as fast as possible
There is a no cost method, a table that maps out where in your code an exception might be required so that it only runs when it is needed, and thus only slows the program using memory when needed (which is unlikely as it is usually a failsafe)
Exception-safe code is where even if an exception is made, it won't affect the program at all
Basic guarantee leaves code valid, strong guarantee guarantees the code will be the same

Assertions
Allows you to abort program if something is true
Simply, assertion is to make sure of something, if that thing is false then stop immediately
Program will terminate with no cleanup, may create a dump
If a bug is unable to be found you can assert if you know what is wrong, break into when the bug is after time
Final release versions of program will usually have asserts cut out via the compiler to allow for a smaller executable
Both happen during runtime, exceptions are for outside of your control issues, assertions are for inside.

No comments:

Post a Comment