Python Exception Handling
Python Exception Handling
This tutorial provides a comprehensive guide to Python exception handling, based on information from
W3Schools (Python Try Except). It covers the essential concepts, including try-except blocks, handling
multiple exceptions, using else and finally blocks, and raising exceptions manually. Each section includes
explanations and practical examples to help beginners understand and apply exception handling
effectively.
In Python, an exception is an error that occurs during program execution, such as trying to access an
undefined variable or dividing by zero. Without handling, these exceptions cause the program to crash
and display an error message. Exception handling allows you to catch these errors and respond
appropriately, ensuring your program continues running or fails gracefully.
The try-except block is the cornerstone of exception handling in Python. The try block contains code that
might raise an exception, while the except block defines how to handle the error.
Syntax
try:
except:
Example
try:
print(x)
except:
Explanation:
The except block catches the error and prints "An exception occurred" instead of crashing.
You can handle different types of exceptions by specifying multiple except blocks, each targeting a
specific exception type. A general except block can catch any unspecified exceptions.
Syntax
try:
except ExceptionType1:
# Handle ExceptionType1
except ExceptionType2:
# Handle ExceptionType2
except:
Example
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
Explanation:
If another type of exception occurs, the general except block handles it.
Exception Type
Description
NameError
TypeError
Raised when an operation is applied to an inappropriate type.
ValueError
Raised when a function receives an argument of the correct type but an invalid value.
ZeroDivisionError
The else block is optional and runs only if no exceptions occur in the try block. It’s useful for code that
should execute only when the try block succeeds.
Syntax
try:
except:
else:
Example
try:
print("Hello")
except:
else:
Explanation:
Since print("Hello") executes without errors, the else block runs, printing "Nothing went wrong."
The finally block is optional and always executes, regardless of whether an exception occurred. It’s
commonly used for cleanup actions, such as closing files or releasing resources.
Syntax
try:
except:
finally:
Example
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
finally:
f.close()
except:
Explanation:
The finally block ensures the file is closed, even if an error occurs while opening or writing to it.
Raising Exceptions
You can manually raise exceptions using the raise keyword to enforce conditions or validate inputs. You
can raise a generic Exception or a specific exception type like TypeError.
Syntax
if condition:
x = -1
if x < 0:
Explanation:
If x is negative, the program raises an exception with the message "Sorry, no numbers below zero."
x = "hello"
Explanation:
If x is not an integer, a TypeError is raised with the message "Only integers are allowed."
Practical Tips
Be Specific: Catch specific exceptions (e.g., NameError, TypeError) before a general except to avoid
masking unexpected errors.
Use Finally for Cleanup: Always close resources like files or database connections in a finally block.
Raise Meaningful Exceptions: Use raise to enforce rules and provide clear error messages.
Test Your Code: Use W3Schools’ “Try It Yourself” links to experiment with the examples and see how
they work.
References
Conclusion
Exception handling is essential for writing robust Python programs. By using try-except blocks, you can
catch and handle errors gracefully. The else block allows you to run code when no errors occur, while
the finally block ensures cleanup actions are performed. Raising exceptions manually with raise gives
you control over error conditions. With these tools, you can build reliable and user-friendly Python
applications.
Note: This tutorial is based on information from W3Schools, specifically the Python Try Except page,
accessed on July 17, 2025.