raise and Custom Exceptions
raise throws an exception. Subclass Exception for your own types and use else and finally with try.
Example
class AgeError(ValueError):
pass
def check(a):
if a < 0:
raise AgeError("negative")
return a
try:
check(-1)
except AgeError as e:
print("caught", e)
else:
print("fine")
finally:
print("done")Result
caught negative done
Exercise
Throw an error.
ValueError("x")Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.