When exceptions go unhandled, Python prints a traceback. Tracebacks are read from the bottom upward. The last line describes what happened and lines above describe where it happened.
Is your Python program printing out a traceback? You have an uncaught exception! You can catch that exception with a try-except block.
Have a specific condition that should loudly crash your program? Use Python's raise statement with an exception object (make sure to provide a helpful error message) to raise an exception!
Python's "invalid syntax" error message comes up often, especially when you're first learning Python. What usually causes this error and how can you fix it?
Python crashed with the error TypeError: can only concatenate str (not "int") to str. Essentially Python's saying you've used + between a string and a number and it's unhappy about it. Let's talk about how to fix this issue and how to avoid it more generally.
Handling an exception and need to access the exception object? Use the as keyword in your except block.
Need to handle multiple types of exceptions at once? Python has a few different ways to catch multiple exception types at once.
You can catch all exceptions implicitly, but it's usually best to be explicit (even when catching all exceptions).
The trickiest programming bugs are often caused by catching exceptions that you didn't mean to catch or handling exceptions in ways that obfuscate the actual error that's occurring. Which exceptions should you catch and which should you leave unhandled?
Re-raising exceptions in Python can be used to log exceptions for troubleshooting, to chain exceptions for clearer context, and to simplify tracebacks by suppressing the original exception.
Continue exploring
Learn something new about Python every week
My name is Trey Hunner. I publish new Python articles and screencasts every week through Python Morsels. If you want to learn something new about Python every week, join Python Morsels!