The Try ... Except Block
What do we do when we don't want to debug our code; we just want to run it without errors?
What do we do when we don't want to debug our code; we just want to run it without errors?
Most programming languages have a way to take care of errors while running a program, usually with some code that tells the interpreter to ignore errors. Python's way is with the try block. Here's how it works:
try:
code...
For example, try running the code below:
"Number: " + 2
Python will produce an error. However, try this:
try:
"Number: " + 2
Python doesn't produce an error. That's because it ran the code inside the try
block and saw an error. It then skipped the rest of the code inside the try block and stopped itself from producing an error.
What if we have code that we only want to run when there is an error? Fortunately, Python includes a solution called the try ... except block. Here's the format:
try:
code...
except:
code to run if there is an error...
The code in the except
block only runs if an error occurs.