Reusable programs · 11 min

Handle exceptions

Recover from expected errors with try and except.

Python raises an exception when an operation cannot complete. A traceback points to the lines involved and ends with the exception type and message. Read that last line first, then look for the line in your own code.

Place the risky operation in try and catch the specific error you can handle. A narrow block keeps unrelated failures visible. Use raise when your function needs to report an invalid value to its caller.

Follow the example

The string represents a word.

Try it yourself

Create a function called whole_number(text) that returns the converted integer or 0 when conversion raises ValueError. Print the results for "12" and "twelve".

Target output

12
0
Show a hint

Put return int(text) inside the try block and return 0 inside the except block.

Output

Ready

Run your code to see the output here.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
def whole_number(text):
    try:
        return int(text)
    except ValueError:
        return 0

print(whole_number("12"))
print(whole_number("twelve"))