Exceptions
Hopefully you will manage to write the program you wanted to, but, for sure, in the process there will be many failures. Don’t worry, it is normal, and Python will try to help you solve them by informing you about the problems.
Resources
- Real Python introductions to exceptions and tracebacks.
- Errors and exceptions in the official Python tutorial.
- Built in exceptions.
Syntax errors
When the Python interpreter finds invalid code it won’t be able to run the program, and it will generate a syntax error. These errors will try to inform you about where the error is in the code, so take a look at it.
Exceptions
Once the program in already running many different kind of problems might arise and Python will throw an exception in those cases.
There are different kind of exceptions.
IndexError. In a sequence, you have tried to access an index out of range.
KeyError. In a mapping, like a dictionary, you have tried to access a key that does not exist.
- ValueError. The arguments given to the function are not correct.
- NameError. A variable has not been found in the available scopes.
- AttributeError is usually raised when you try to use a method or a property, an attribute, that the object does not have.
All these exceptions are accompanied by a traceback that informs you about the calls that have been done in the program up until the exceptions happened.
Traceback (most recent call last):
File "/home/jose/tmp/curso/file.py", line 4, in <module>
do_division()
File "/home/jose/tmp/curso/file.py", line 2, in do_division
return 1 / 0
~~^~~
ZeroDivisionError: division by zero
Exception control
Sometimes you are expecting that an exception might happen and you can deal with it. You can catch and deal with the exception using try and except.
Do not write excepts without an particular exception type to catch. In general that would be a very bad practice because the exception catched could be an unexpected one.