Exceptions: try, except, finally
Catching errors, raise and the with statement.
All lessons · Python lessons: learn from scratch
try and except
An exception is an error raised while the program runs. If you do not catch it the program stops. Put risky code in try and say in except what to do. Catch the most specific error type you can.
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
print(safe_divide(10, 2)) # 5.0
print(safe_divide(1, 0)) # Noneelse and finally
else runs only when there was no error. finally runs either way and suits clean-up work such as closing a file.
try:
value = int("42")
except ValueError:
print("not a number")
else:
print("parsed", value)
finally:
print("done")Raising your own errors
If a function receives a bad value, use raise to signal a clear error. For more precision you can define your own error class.
class NegativeAmount(Exception):
pass
def withdraw(balance, amount):
if amount < 0:
raise NegativeAmount("amount must be positive")
return balance - amount
try:
withdraw(50, -5)
except NegativeAmount as err:
print("Error:", err)- Avoid a bare except:, it hides bugs.