try and except
Programs crash when something unexpected happens, like dividing by zero or converting bad text to a number. The try and except keywords let you catch these problems and keep your code running.
Sometimes Python code crashes. Dividing by zero, asking for an item that doesn't exist, converting bad text to a number — each one stops the program with an error.
Here is what an unhandled error looks like:
The line after the crash never ran. Python raised a ValueError and stopped. To keep your program running, you wrap risky code in a try block.
The basic syntax pairs try with except:
Now the same code finishes cleanly:
What will be the output?
A bare except catches everything, but that hides bugs. It's almost always better to name the exact exception you expect.
Here we only catch ValueError:
The conversion succeeded, so the except block was skipped. Common built-in exceptions you'll meet often are ValueError, TypeError, IndexError, KeyError, and ZeroDivisionError.
What will be the output?
Once the except runs, the program keeps going:
What will be the output?
If the exception you raise doesn't match the one you catch, Python still crashes. The except clause is picky about types.
A ValueError catch will not stop a ZeroDivisionError:
What will be the output?
What will be the output?
What will be the output?
What will be the output?