For Python 2.6 and later and Python 3.x:

except Exception as e: print(e)

For Python 2.5 and earlier, use:

except Exception,e: print str(e)
Answer from jldupont on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
Print one message if the try block raises a NameError and another for other errors: try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") Try it Yourself » · See more Error types in our Python Built-in Exceptions Reference.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.4 documentation
Most exceptions are not handled by programs, however, and result in error messages as shown here: >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in <module> 10 * (1/0) ~^~ ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in <module> 4 + spam*3 ^^^^ NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> '2' + 2 ~~~~^~~ TypeError: can only concatenate str (not "int") to str
Discussions

How do I print an exception in Python? - Stack Overflow
How do I print the error/exception in the except: block? try: ... except: print(exception) More on stackoverflow.com
🌐 stackoverflow.com
python - What is more Pythonic way to handle try-except errors? - Software Engineering Stack Exchange
But in your code the error is ignored and it implicitly returns None if the key is not found. If this is what you want, then it can be done simpler with the get() method: ... "Handling" an error by just logging a message and then continuing as if nothing happened, is a terrible antipattern from the Java world which has no place in Python. Exceptions ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
python exception message capturing - Stack Overflow
Beware that except BaseException ... work in Python3, but it won't catch KeyboardInterrupt for instance (which can be very convenient if you want to be able to interrupt your code!), whereas BaseException catches any exception. See this link for the hierarchy of exceptions. 2018-06-18T21:52:36.5Z+00:00 ... If you want the error class, error message, and stack trace, use ... More on stackoverflow.com
🌐 stackoverflow.com
python - Is it correct to use a return statement within a try and except statement? - Stack Overflow
If I have such code in the end of function: try: return map(float, result) except ValueError, e: print "error", e Is it correct to use try / except in return part of method? Is there a wis... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-try-except
Python Try Except - GeeksforGeeks
July 23, 2025 - The error is: unsupported operand type(s) for //: 'int' and 'str' The error is: integer division or modulo by zero · In Python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception. ... # Program to depict else clause with try-except # Function which returns a/b def AbyB(a , b): try: c = ((a+b) // (a-b)) except ZeroDivisionError: print ("a/b result in 0") else: print (c) # Driver program to test above function AbyB(2.0, 3.0) AbyB(3.0, 3.0)
🌐
freeCodeCamp
freecodecamp.org › news › python-print-exception-how-to-try-except-print-an-error
Python Print Exception – How to Try-Except-Print an Error
March 15, 2023 - In this article, you’ll learn how to use that try…except syntax to handle exceptions in your code so they don’t stop your program from running. ... In Python, an exception is an error object. It is an error that occurs during the execution of your program and stops it from running – subsequently displaying an error message...
🌐
Python Land
python.land › home › language deep dives › python try except: examples and best practices
Python Try Except: Examples And Best Practices • Python Land Tutorial
January 29, 2026 - If you removed the try.. except from the code completely and then try to write to the file in read-only mode, Python will catch the error, force the program to terminate, and show this message: Traceback (most recent call last): File “tryexcept.py”, line 3, in
Top answer
1 of 3
5

Neither of these is more Pythonic than the other. The examples are too trivial to say which is preferrable but it really all depends on how things should work.

Catch and logging/reporting an issue is just a hair's breadth away from squashing exceptions which is almost always a terrible idea. The only reason I can see doing this is that you want whatever the issue is to not stop execution. If you are going to do something like this, it's really crucial to make sure that you return something sensible that works for the caller. If the next thing that happens is that the calling code throws its own exception because e.g., None doesn't have an add method, you are at best just making things harder to troubleshoot. It could be a lot worse, however. A lot of serious bugs are due to returning nulls/None after catching an error. I think there are times that is makes sense to do this, but they are rare in my experience.

Allowing the raw exception to bubble out is the next least-worst option, IMO. This can be fine if you are building something small where it will be easy to find the what the problem is when things crash with a KeyError. In a situation where you are leveraging a lot of duck-typing, passing around function references, or using annotations, it can sometimes be difficult. For example, if you are using this code behind a web endpoint, what HTTP error code should you use when you catch a KeyError. 500 might be the right answer in most cases but there might be times you want to produce something else depending on where the key was not found.

That brings me to the last option which you don't mention: catch and raise a separate, more meaningful error. That allows you to distinguish between say, a KeyError thrown because the request was for something that isn't valid and a KeyError thrown because of a bad configuration.

2 of 3
4

Neither is pythonic. Pythonic code would be:

my_dict = {}
def fetch_value(key):
    return my_dict[key]

val = fetch_value('my_key')

Remember, simple is better than complex and flat is better than nested. Since your except-block does not handle the exception in any meaningful way, it is better to just let it bubble up the call stack and terminate the program.

But in your code the error is ignored and it implicitly returns None if the key is not found. If this is what you want, then it can be done simpler with the get() method:

def fetch_value(key):
    return my_dict.get(key)

"Handling" an error by just logging a message and then continuing as if nothing happened, is a terrible antipattern from the Java world which has no place in Python. Exceptions should only be caught if they can be meaningfully handled.

Find elsewhere
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
December 1, 2024 - What you didn’t get to see was the type of error that Python raised as a result of the function call. In order to see exactly what went wrong, you’d need to catch the error that the function raised. The following code is an example where you capture the RuntimeError and output that message to your screen: ... # ... try: linux_interaction() except RuntimeError as error: print(error) print("The linux_interaction() function wasn't executed.")
🌐
Finxter
blog.finxter.com › home › learn python blog › how to print exception messages in python (try-except)
How to Print Exception Messages in Python (Try-Except) - Be on the Right Side of Change
October 30, 2023 - try: x = 1 / 0 except Exception as e: print(e) print("Program continues...") In this example, we attempt to perform a division by zero, which will raise a ZeroDivisionError. The error message is printed, but the program continues to execute subsequent code. ... Printing the exception in a single line of code in Python involves utilizing string formatting within the print() function to display a succinct and clear error message.
🌐
Python Tutorial
pythontutorial.net › home › python basics › python try…except
Python Try Except: How to Handle Exceptions More Gracefully
March 30, 2025 - try: # get input net sales print('Enter the net sales for') previous = float(input('- Prior period:')) current = float(input('- Current period:')) # calculate the change in percentage change = (current - previous) * 100 / previous # show the result if change > 0: result = f'Sales increase {abs(change)}%' else: result = f'Sales decrease {abs(change)}%' print(result) except ValueError: print('Error! Please enter a number for net sales.') Code language: Python (python) When you run a program and enter a string for the net sales, you’ll get the same error message. However, if you enter zero for
Top answer
1 of 3
13

Keep it simple: no try block

It took me a while to learn, that in Python it is natural, that functions throw exceptions up. I have spent too much effort on handling these problems in the place the problem occurred.

The code can become much simpler and also easier to maintain if you simply let the exception bubble up. This allows for detecting problems on the level, where it is appropriate.

One option is:

try:
    return map(float, result)
except ValueError, e:
    print "error", e
    raise

but this introduces print from within some deep function. The same can be provided by raise which let upper level code to do what is appropriate.

With this context, my preferred solution looks:

return map(float, result)

No need to dance around, do, what is expected to be done, and throw an exception up, if there is a problem.

2 of 3
2

If you surround the code block containing a return statement with an try/except clause, you should definitely spend some thoughts of what should be returned, if an exception actually occurs:

In you example, the function will simply return None. If it's that what you want, I would suggest to explicitely add a return None like

except ValueError, e:
    print "error", e
    return None

in your except block to make that fact clear.

Other possibilities would be to return a "default value" (empty map in this case) or to "reraise" the exception using

except ValueError, e:
    print "error", e
    raise

It depends on how the function is used, under what circumstances you expect exceptions and on your general design which option you want to choose.

🌐
Rollbar
rollbar.com › home › throwing exceptions in python
How to Throw Exceptions in Python | Rollbar
July 31, 2023 - Here’s an example of Python’s “try-except” (often mistakenly referred to as “try-catch-exception”). Let’s say we want our code to run only if the Python version is 3. Using a simple assertion in the code looks like this: import sys assert (sys.version_info[0] == 3), "Python version must be 3" If the of Python version is not 3, the error message looks like this:
🌐
Server Academy
serveracademy.com › blog › python-try-except
Python Try Except - Blog - ServerAcademy.com
November 12, 2024 - When writing Python code, errors can be frustrating. Luckily, Python’s and blocks provide an effective way to manage errors without breaking the flow of your co
🌐
Programiz
programiz.com › python-programming › exception-handling
Python Exception Handling (With Examples)
In Python, the finally block is always executed no matter whether there is an exception or not. The finally block is optional. And, for each try block, there can be only one finally block. ... try: numerator = 10 denominator = 0 result = numerator/denominator print(result) except: print("Error: Denominator cannot be 0.") finally: print("This is finally block.")
🌐
Justin Joyce
justinjoyce.dev › home › latest › python try except
Python try except | Justin Joyce
February 18, 2024 - Try and except are the building blocks of exception handling in Python. You’ll also sometimes see finally and else. Here’s the summary: ... You’ll usually see try and except by themselves; finally is used less often, and else even less. Here’s a (slightly) more realistic example: me = {"name": "justin"} def get_age(person): try: return person["age"] except KeyError as e: print(f"caught key error: {e}") # There's no 'age' key on the dict get_age(me) # caught key error: 'age'
🌐
Reddit
reddit.com › r/learnpython › what happens when you use try and except statements in a function that both have a return statement in them but you also have a finally statement?
r/learnpython on Reddit: What happens when you use try and except statements in a function that both have a return statement in them BUT you also have a finally statement?
May 30, 2023 -

Ok, that was an awful title and I'm sorry... but it's hard to phrase! My question overall is, if we use a try statement in a function (and let's imagine it works, we don't end up having to handle any exceptions) and there is a return statement in this try-block. Won't that cause us to leave the function? Since, we are returning control back to main, let's say.

But, we have a finally statement in our function to. It might do something trivial like print something. Does this get executed even though we should have hit return?

Now, I have tested this. And what it seems to do is reach the return statement, ignore it, carry out the finally statement and then go back to the return. But I would like to know if I am understanding this correctly.

🌐
Python Basics
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
The try except statement can handle exceptions. Exceptions may happen when you run a program. Exceptions are errors that happen during execution of the program. Python won't tell you about errors like syntax errors (grammar faults), instead it will abruptly stop.
🌐
Medium
medium.com › @mathur.danduprolu › handling-errors-in-python-try-except-custom-exceptions-and-more-26a6aa436d20
Handling Errors in Python: Try-Except, Custom Exceptions, and More | by Mathur Danduprolu | Medium
October 30, 2024 - Explanation: In the above code, the try block contains code that could cause an error. If a ZeroDivisionError occurs, the except block will execute, avoiding program termination. Keywords: try-except in Python, Python exception handling, catching errors in Python, ZeroDivisionError