Recover with Try and Except
Core idea
Place the operation that may fail inside try. If it raises a matching exception, execution jumps to the associated except block; the remaining statements in try are skipped. A handler can bind the exception object with as error.
try: count = int("many")except ValueError: count = 0print(count)Invalid conversion selects the fallback zero. Use a fallback only when the application contract allows it.
Successful conversion
try: count = int("12")except ValueError: count = 0print(count)No exception occurs, so the handler is skipped.
Inspect the exception
try: int("?") print("Converted")except ValueError as error: print(type(error).__name__)The print in try is skipped. The handler prints the class name using the class attribute __name__.
Common mistake
Do not put unrelated operations under a broad handler: it can turn programming bugs into apparently valid fallback results.
Practice
Write a function that converts a string to an integer, returning -1 only for invalid conversion. Test valid zero, negative and invalid text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Recover from conversion failures
Check your understanding of try and except.
What is printed?
try: n = int("x")except ValueError: n = 0print(n)What is printed?
try: n = int("-2")except ValueError: n = 0print(n)What is printed?
try: int("bad") print("converted")except ValueError: print("recovered")Why keep a try block narrow?