Python Try...Except
The try
block lets you test a block of code for errors, while the except
block lets you handle the error. Below is a list of common exceptions in Python, and clicking on each will scroll you to the explanation and examples.
Common Python Exceptions
- ZeroDivisionError: Raised when division or modulo by zero occurs.
- TypeError: Raised when an operation is applied to an object of an inappropriate type.
- ValueError: Raised when a built-in operation or function receives an argument with the right type but inappropriate value.
- IndexError: Raised when a sequence subscript is out of range.
- KeyError: Raised when a dictionary key is not found in the dictionary.
- FileNotFoundError: Raised when trying to open a file that does not exist.
- AttributeError: Raised when an invalid attribute reference or assignment is made.
- ImportError: Raised when an import statement fails.
- OSError: Raised for system-related errors like file operations.
- RuntimeError: Raised when an error is detected that doesn't fall into any of the other categories.
ZeroDivisionError
This error occurs when a number is divided by zero. For example:
# ZeroDivisionError example
try:
result = 5 / 0
except ZeroDivisionError:
print("Error: You cannot divide by zero!")
Output
Error: You cannot divide by zero!
TypeError
This error occurs when an operation is applied to an object of an inappropriate type. For example:
# TypeError example
try:
result = '5' + 5
except TypeError:
print("Error: You cannot add a string and an integer!")
Output
Error: You cannot add a string and an integer!
ValueError
This error occurs when a built-in operation or function receives an argument with the right type but inappropriate value. For example:
# ValueError example
try:
num = int("abc")
except ValueError:
print("Error: Invalid literal for int()!")
Output
Error: Invalid literal for int()!
IndexError
This error occurs when trying to access an index that is out of range in a list. For example:
# IndexError example
try:
items = [1, 2, 3]
print(items[5])
except IndexError:
print("Error: Index is out of range!")
Output
Error: Index is out of range!
KeyError
This error occurs when trying to access a key in a dictionary that does not exist. For example:
# KeyError example
try:
my_dict = {"name": "Karthick"}
print(my_dict["age"])
except KeyError:
print("Error: Key 'age' not found in dictionary!")
Output
Error: Key 'age' not found in dictionary!
FileNotFoundError
This error occurs when trying to open a file that does not exist. For example:
# FileNotFoundError example
try:
f = open("non_existent_file.txt")
except FileNotFoundError:
print("Error: File not found!")
Output
Error: File not found!