
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Difference Between except: and except Exception as e:
The except: statement catches all exceptions, including system-exiting ones, which can be dangerous. On the other hand, except Exception as e: catches only standard exceptions and lets you inspect the error safely. It is the preferred and safer approach in modern Python.
except: (Bare Exception Handling)
This catches all exceptions including system-exiting ones like KeyboardInterrupt and SystemExit. It is not recommended because it hides all errors and makes debugging difficult.
In this example, we use a bare except: to catch any error, but it makes it harder to identify the exact issue -
try: x = 1 / 0 except: print("Some error occurred")
We get the output as shown below -
Some error occurred
except Exception as e: (Recommended Style)
This catches only exceptions that inherit from Exception, which excludes system-exiting exceptions. It is safe, clean, and lets you inspect the actual error.
Here, we use except ZeroDivisionError as e: to catch the specific error and print the message, making it easier to debug -
try: x = 1 / 0 except ZeroDivisionError as e: print("Error:", e)
Following is the output of the above code -
Error: division by zero
Using except Exception as e (Modern Python)
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)
We get the outout as shown below -
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)
The output obtained is as shown below -
Invalid conversion: invalid literal for int() with base 10: 'abc'
Example: Printing Exception Type
In the following example, we are importing a non-existent module and printing the exception type. This helps us understand the nature of the error -
try: import non_existing_module except ModuleNotFoundError as e: print("Error type:", type(e))
The result produced is as follows -
Error type: <class 'ModuleNotFoundError'>
Using except Exception e (Invalid in Python 3)
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)
Following is the output of the above code -
File "/home/cg/root/68237f533b155/main.py", line 3 except ZeroDivisionError e: ^ SyntaxError: invalid syntax
What About 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.
Example: Python 2 Style (No longer valid)
In this example, we use the Python 2-style comma to catch the error. In Python 3, this raises a syntax error -
try: print 1 / 0 except ZeroDivisionError, e: print "Caught:", e
After executing the above code in Python 2, we get the following output -
Caught: integer division or modulo by zero
Why is e required in Python 3
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:.
By using as, the syntax clearly shows that the exception object is being stored in a variable for further inspection. This not only avoids the misuse of tuple unpacking but also aligns with other parts of the language, like with open(...) as f.
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)
The result produced is -
Handled: invalid literal for int() with base 10: 'abc'
Best Practices for Exception Handling
Writing clean and reliable error-handling code is important for debugging Python applications. Following are some best practices to follow when using try-except blocks -
Avoid Bare except: Blocks
Do not use except: without specifying an exception type. It catches all errors, including KeyboardInterrupt and SystemExit, and may hide bugs.
Example: Bare except (not recommended)
In this example, any error will be caught silently, even critical ones like program interrupts, making debugging difficult -
try: value = int("abc") except: print("Some error occurred")
We can see the output below -
Some error occurred
Use except Exception as e: for Detailed Information
This lets you access the exception object, so you can log or display the actual error message for better debugging.
Example: Using as e to get error details
The following code catches the error and prints a meaningful message -
try: number = int("xyz") except ValueError as e: print("Invalid input:", e)
It prints the following message -
Invalid input: invalid literal for int() with base 10: 'xyz'
Handle Specific Exceptions When Possible
Always catch the exact exception you expect to avoid accidentally handling unrelated errors. This makes your code safer and easier to maintain.
Example: Catching a specific exception
This code catches only ZeroDivisionError and allows other errors to raise normally -
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero")
The error is displayed as follows -
Cannot divide by zero
Use finally for Cleanup Code
The finally block runs whether or not an exception occurred. It is useful for closing files or releasing resources.
Example: Using finally
In this example, the finally block runs regardless of whether an exception occurred, ensuring cleanup actions happen -
# Creating the file and writing some content with open("data.txt", "w") as file: file.write("This is a sample text file.") # Now trying to read the file try: file = open("data.txt", "r") data = file.read() print("File content:", data) except FileNotFoundError as e: print("File not found:", e) finally: print("Closing file or cleaning up") file.close()
Following is the output obtained -
File content: This is a sample text file. Closing file or cleaning up
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. Stick to the modern style, handle specific exceptions, and follow best practices for clean and maintainable error handling.