Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between \'except Exception as e\' and \'except Exception, e\' in Python?
You can handle errors in Python using the try and except blocks. Sometimes, we also want to store the actual exception in a variable to print it or inspect it. This is done using the as keyword in modern Python. But if you have seen older code, you might find except Exception e or even except Exception, e being used.
In this article, we will explore the difference between these syntaxes, understand why older ones no longer work in Python 3, and learn the best practices for clean exception handling.
Understanding Basic Exception Handling
Python provides try-except blocks to catch and handle errors during runtime. The basic syntax looks like this ?
try:
# code that may raise an error
except SomeError:
# code that runs if the error occurs
You can also store the exception in a variable using as to understand or log it ?
try:
# code that may raise an error
except SomeError as e:
print(e)
Modern Python: except Exception as e
This is the correct syntax in Python 3. The as keyword assigns the exception to a variable so we can access its message or type.
Example: Catching ZeroDivisionError
In this example, we catch the ZeroDivisionError and print the error message, helping us understand the cause of the issue ?
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Caught an error:", e)
Caught an error: division by zero
Example: Catching ValueError
In this example, we are trying to convert a string to an integer and catching the ValueError using as e ?
try:
number = int("abc")
except ValueError as e:
print("Invalid conversion:", e)
Invalid conversion: invalid literal for int() with base 10: 'abc'
Invalid Python 3 Syntax: except Exception e
This syntax was used in older versions of Python (specifically Python 2). In Python 3, it is not allowed and will raise a SyntaxError.
Example: Invalid Syntax in Python 3
This code tries to catch the error without using as, which results in a syntax error in Python 3 ?
try:
x = 1 / 0
except ZeroDivisionError e:
print("Error:", e)
File "main.py", line 3
except ZeroDivisionError e:
^
SyntaxError: invalid syntax
Python 2 Style: except Exception, e
This comma syntax was allowed in Python 2, where you could assign the error to a variable using a comma. But in Python 3, this also results in a syntax error.
Python 2 Example (No longer valid)
In Python 2, you could use this syntax, but it's now deprecated ?
# Python 2 only - will not work in Python 3
try:
print 1 / 0
except ZeroDivisionError, e:
print "Caught:", e
Why Python 3 Requires "as"
In Python 2, exceptions could be assigned to a variable using a comma, like except Exception, e:. However, this syntax created ambiguity because the comma operator could also be used for tuple unpacking, making it hard to clearly understand the intention of the code.
To eliminate this confusion, Python 3 introduced a more explicit and readable way of assigning the exception object to a variable using the as keyword, as in except Exception as e:.
How to Fix Old Python 2 Code
If you are working with old Python code, replace all cases of except SomeError, e: with except SomeError as e:
Example: Updated Code
In this example, we fix the old Python 2-style code by using as e, ensuring compatibility with Python 3 ?
try:
value = int("abc")
except ValueError as e:
print("Handled:", e)
Handled: invalid literal for int() with base 10: 'abc'
Best Practices
Use Specific Exception Types
Always catch the exact exception you expect to avoid accidentally handling unrelated errors ?
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero:", e)
Cannot divide by zero: division by zero
Avoid Bare except Blocks
Do not use except: without specifying an exception type. It catches all errors, including KeyboardInterrupt and SystemExit ?
# Not recommended
try:
value = int("abc")
except:
print("Some error occurred")
# Better approach
try:
value = int("abc")
except ValueError as e:
print("Invalid input:", e)
Some error occurred Invalid input: invalid literal for int() with base 10: 'abc'
Comparison
| Syntax | Python Version | Status |
|---|---|---|
except Exception as e: |
Python 3 | ? Valid & Recommended |
except Exception e: |
Python 2 (old) | ? SyntaxError in Python 3 |
except Exception, e: |
Python 2 | ? SyntaxError in Python 3 |
Conclusion
The correct way to catch and name an exception in Python 3 is except Exception as e. Older forms like except Exception e or except Exception, e are invalid and will raise syntax errors. Always use specific exception types and the as keyword for clean, maintainable error handling.
