Codele / Advanced programming
Errors and exceptions
Sometimes a line cannot do its job. The code stops what it is doing and throws the problem up the chain of callers, like a hot potato, until someone catches it.
- An exception is a problem that is thrown (Python says raise). The code stops at that line and the problem travels back up through the callers, skipping every line it leaves behind.
- catch (Python says except) is where a caller stops the problem and decides what to do. If nobody catches it, the whole program stops with an error message.
- finally runs whether or not anything was thrown, so cleanup always happens. C++ has no finally: its cleanup is done by objects that tidy up when they go out of scope.
- Go has no exceptions. A function returns its answer and an error value, and the caller checks it with if err != nil. Same idea, but you pass the problem up by hand with return. Go’s defer is the nearest thing to finally.
Loading the playable lesson…