This is a full list of exceptions: https://docs.python.org/3/library/exceptions.html#bltin-exceptions.
There are two different types of exceptions: ones that happen when the program is being parsed by Python (
IndentationError), and ones that happen when the program is running (runtime exceptions).
Raising an exception
raise statement. Example:
>>> while True: ... num = int(input("Enter a number between 1 and 10:\n")) ... if not 1 <= num <= 10: ... raise ValueError("Number out of range") ... Enter a number between 1 and 10: 5 Enter a number between 1 and 10: 0 Traceback (most recent call last): ... ValueError: Number out of range
Handling an exception
Runtime exceptions can be caught. We use the
except construct to handle an exception. If an error is encountered in the
try block, execution stops and is transferred to the except block.
>>> try: ... print(1/0) ... except ZeroDivisionError: ... print("Can't divide by zero!") ... Can't divide by zero!
There can be multiple
except clauses for different types of exceptions. An
except clause can also not have an exception specified, in which case it would handle all runtime exceptions. Example:
>>> try: ... lst = None ... lst.append(2) ... except: ... print("Something bad happened!") ... Something bad happened!