Raising exceptions
So what is an exception, really? Technically, an exception is just an object. There are many different exception classes available and we can easily define more of our own. The one thing they all have in common is that they derive from a built-in class called BaseException
.
These exception objects become special when they are handled inside the program's flow of control. When an exception occurs, everything that was supposed to happen doesn't happen, unless it was supposed to happen when an exception occurred. Make sense? Don't worry, it will!
So then, how do we cause an exception to occur? The easiest way is to do something stupid! Chances are you've done this already and seen the exception output. For example, any time Python encounters a line in your program that it can't understand, it bails with a SyntaxError
, which is a type of exception. Here's a common one:
>>> print "hello world" File "<stdin>", line 1 print "hello world" ...