Introduction to Errors and Exceptions
In Python, there are two main kinds of errors: syntax errors and exceptions.
● Syntax Errors: These are parsing errors and occur when you have a statement
that is not valid Python code. The program will not even begin to execute.
# Example of a syntax error
if x > 5
print("x is greater than 5")
In the code above, the missing colon (:) after the if condition is a syntax error.
● Exceptions: These are errors that occur during the execution of the program.
Even if your code is syntactically correct, it may cause an error when it runs.
# Example of an exception
print(10 / 0)
This code is syntactically correct, but it will raise a ZeroDivisionError when
executed.
The try and except Blocks
The fundamental way to handle exceptions in Python is with the try...except block.
● The try block contains the code that might raise an exception.
● The except block contains the code that will be executed if an exception of a
specific type occurs in the try block.
Basic Syntax:
try:
# Code that may cause an exception
x = int(input("Enter a number: "))
result = 10 / x
print(f"The result is: {result}")
except:
# Code to run when any exception occurs
print("An error occurred!")
Handling Specific Exceptions
It's generally a good practice to handle specific exceptions rather than using a bare
except clause. This allows you to respond differently to different types of errors.
You can have multiple except blocks to handle different exceptions:
try:
x = int(input("Enter a number: "))
result = 10 / x
print(f"The result is: {result}")
except ValueError:
print("Invalid input! Please enter an integer.")
except ZeroDivisionError:
print("You cannot divide by zero!")
You can also handle multiple exceptions in a single except block by passing a tuple of
exception types:
try:
x = int(input("Enter a number: "))
result = 10 / x
print(f"The result is: {result}")
except (ValueError, ZeroDivisionError):
print("An error occurred with your input.")
You can also get a reference to the exception object by using the as keyword:
try:
x = int(input("Enter a number: "))
result = 10 / x
print(f"The result is: {result}")
except Exception as e:
print(f"An error occurred: {e}")
The else Block
The else block is optional and, if present, is executed only if the try block completes
without raising an exception.
try:
x = int(input("Enter a number: "))
result = 10 / x
except ZeroDivisionError:
print("You cannot divide by zero!")
else:
print(f"The result is: {result}")
In this example, if the user enters 0, the except block will execute. If the user enters
any other number, the else block will execute.
The finally Block
The finally block is also optional and, if present, is always executed, whether an
exception occurred or not. This is useful for cleanup operations, like closing a file.
file = None
try:
file = open("my_file.txt", "r")
data = file.read()
print(data)
except FileNotFoundError:
print("The file was not found.")
finally:
if file:
file.close()
print("File closed.")
Raising Exceptions (raise)
You can raise exceptions in your own code using the raise keyword. This is useful
when you want to signal that an error has occurred based on some condition.
You can raise a built-in exception:
def get_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age
try:
user_age = get_age(-5)
print(f"The user's age is: {user_age}")
except ValueError as e:
print(e)
You can also define your own custom exceptions by creating a new class that inherits
from the base Exception class:
class MyCustomError(Exception):
pass
def my_function(value):
if value == "bad":
raise MyCustomError("This is a custom error.")
return value
try:
my_function("bad")
except MyCustomError as e:
print(e)
Common Built-in Exceptions
Here is a table of some of the most common built-in exceptions in Python:
Exception Description
SyntaxError Raised by the parser when a syntax error is
encountered.
IndentationError Raised when there is incorrect indentation.
NameError Raised when a variable is not found in the local
or global scope.
TypeError Raised when an operation or function is applied
to an object of the wrong type.
ValueError Raised when a function receives an argument
of the correct type but an invalid value.
ZeroDivisionError Raised when the second operand of a division
or modulo operation is zero.
IndexError Raised when a sequence subscript is out of
range.
KeyError Raised when a dictionary key is not found.
FileNotFoundError Raised when a file or directory is requested but
cannot be found.
AttributeError Raised when an attribute reference or
assignment fails.
ImportError Raised when an import statement has trouble
trying to load a module.
ModuleNotFoundError A subclass of ImportError, raised when a
module could not be located.