Exception Handling in Python
Catch and handle errors with try / except / else / finally, and raise your own.
Easy
try:
value = int(text)
except ValueError:
print("Not a number")
else:
print("Parsed", value) # only if no exception
finally:
print("Always runs")
Catch specific exceptions, not a bare except:, so real bugs aren't hidden. Raise your own with raise ValueError("resistance must be positive"), or define custom classes that inherit from Exception.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.