You have to define which type of exception you want to catch. So write except Exception as e: instead of except, e: for a general exception.

Other possibility is to write your whole try/except code this way:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e:      # works on python 3.x
    logger.error('Failed to upload to ftp: %s', repr(e))

In older versions of Python 2.x, use except Exception, e instead of except Exception as e:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to %s', FTPADDR)
except Exception, e:        # works on python 2.x
    logger.error('Failed to upload to ftp: %s', repr(e))
Answer from eumiro on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-print-exception
Python Print Exception - GeeksforGeeks
July 23, 2025 - Explanation: This code tries to convert the string "text" into an integer, which isn’t possible and raises a ValueError. The except block catches the error, prints its type using type(e) and displays the error message using e.
Discussions

How would I get my error message to print before Python errors?
That error is a python2 error. The easiest fix is to use python3 instead. More on reddit.com
🌐 r/learnpython
11
7
January 1, 2021
Print exception notes - in repr(exc) or otherwise - Ideas - Discussions on Python.org
Exception notes are printed in tracebacks, but they are omitted when an exception is handled and logged or printed. I think a possibly helpful information is lost. # Python 3.11+ enote = ValueError("error message") enot… More on discuss.python.org
🌐 discuss.python.org
0
September 4, 2024
What’s the correct way to print an exception in Python when handling errors? - Ask a Question - TestMu AI (formerly LambdaTest) Community
I’m a bit confused about the proper way to display errors when using a try/except block in Python. I’m catching exceptions successfully, but I’m not sure how to actually print the exception in a meaningful way. Right now, my except block runs, but I don’t know how to access or display ... More on community.testmuai.com
🌐 community.testmuai.com
0
December 22, 2025
Try/Except isn't printing my message
Except is used for catching exceptions, but your code does not appear to throw any exceptions. I believe instead of the try and except, you want to use an else:. More on reddit.com
🌐 r/learnpython
8
7
August 18, 2023
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
The exception’s __str__() output is printed as the last part (‘detail’) of the message for unhandled exceptions.
🌐
Reddit
reddit.com › r/learnpython › how would i get my error message to print before python errors?
r/learnpython on Reddit: How would I get my error message to print before Python errors?
January 1, 2021 -

I am trying to make a pay calculator to calculate overtime, and my calculator is set up like this:

https://hastebin.com/wehuroruzi.py

From line 14 to 19 I state that If the 'pay_rate' input from the user isn't an integer or float point, then send an error message saying that the user must supply a number.

My issue is that Python gives me an error before the message can be sent to the user. The error being that whatever string that the user sent has no definition in the code.

🌐
Coursera
coursera.org › tutorials › how to catch, raise, and print a python exception
How to Catch, Raise, and Print a Python Exception | Coursera
August 13, 2024 - The method above demonstrates how to catch all exceptions in Python. However, many different types of errors can arise from the code you put inside the try block. If you don’t specify which exceptions a particular except clause should catch, it will handle each one the same way. You can address this issue in a few ways. For example, you can anticipate the errors that may occur and add corresponding except blocks for each one. ... 1 2 3 4 5 6 7 8 9 10 11 12 a = 5 b = "zero" try: quotient = a / b print(quotient) except ZeroDivisionError: print("You cannot divide by zero") except TypeError: print("You must convert strings to floats or integers before dividing") except NameError: print("A variable you're trying to use does not exist")
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
March 18, 2026 - Additionally, the error message gives you a hint about what went wrong. In this example, there was one bracket too many. Remove it and run your code again: ... >>> print(0 / 0) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero · This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python ...
Find elsewhere
🌐
Python.org
discuss.python.org › ideas
Print exception notes - in repr(exc) or otherwise - Ideas - Discussions on Python.org
September 4, 2024 - Exception notes are printed in tracebacks, but they are omitted when an exception is handled and logged or printed. I think a possibly helpful information is lost. # Python 3.11+ enote = ValueError("error message") enote.add_note("additional info") try: raise enote except Exception as exc: print(repr(exc)) # will NOT print 'additional info' Unless I overlooked something, the PEP 678 does not discuss the string representation, just the tracebacks.
🌐
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 - For example, if you have a large ... try block and handle a possible error in the except block: try: print("Here's variable x:", x) except: print("An error occured") # An error occured...
🌐
JanBask Training
janbasktraining.com › community › python-python › catch-and-print-full-python-exception-traceback-without-haltingexiting-the-program
Catch and print full Python exception traceback without halting/exiting the program | JanBask Training Community
November 2, 2025 - Logging Instead of Printing (Recommended for real apps) ... import logging, traceback logging.basicConfig(filename="errors.log", level=logging.ERROR) try: open("unknownfile.txt") except Exception as e: logging.error("Exception occurred: %s", traceback.format_exc()) ... By combining try-except with the traceback module, you maintain full visibility into errors while keeping your program alive — a powerful technique for building resilient Python applications.
🌐
Esri Community
community.esri.com › t5 › python-questions › what-is-best-way-to-get-an-error-message-in-python › td-p › 370869
What is Best Way to Get an Error Message in Python... - Esri Community
December 11, 2021 - Looking at that documentation, one can see that EnvironmentError is "the base class for exceptions that can occur outside the Python system. For environment errors, 2 items are typically returned: errno and strerror. My guess is that the errors you are missing with your original code are environment errors. I am guessing if you trap and handle environment errors separately, your code will work fine. For example, something along the lines of: try: # some code except EnvironmentError, ee: print ee.strerror except Exception, e: print e.message‍‍‍‍‍‍
🌐
Tagline Infotech
taglineinfotech.com › home › how do i print an exception in python?
How do I Print an Exception in Python? - Tagline Infotech
December 31, 2025 - Master print an exception in Python with 'traceback' module. Customize messages for effective debugging.
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › python-try-except-print-error
How to print as exception in Python
July 31, 2023 - Traceback (most recent call last): ... ‘variable_that_does_not_exist’ is not defined The traceback.format_exc() function will print a detailed stack trace of the exception....
🌐
Codemia
codemia.io › home › knowledge hub › how do i print an exception in python?
How do I print an exception in Python? | Codemia
September 23, 2025 - It shows the line where the exception happened and the call path that led there. That makes it much more useful than print(exc) when the failure is inside a deeper call stack. For real applications, printing directly to standard output is often not enough. Python’s logging module is usually the better choice because it captures structured messages and can write to files, consoles, or centralized log systems.
🌐
TestMu AI Community
community.testmuai.com › ask a question
What’s the correct way to print an exception in Python when handling errors? - Ask a Question - TestMu AI (formerly LambdaTest) Community
December 22, 2025 - I’m a bit confused about the proper way to display errors when using a try/except block in Python. I’m catching exceptions successfully, but I’m not sure how to actually print the exception in a meaningful way. Right no…
Top answer
1 of 16
1534

traceback.format_exc() will yield more info if that's what you want.

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

This outputs:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception
2 of 16
880

Some other answer have already pointed out the traceback module.

Please notice that with print_exc, in some corner cases, you will not obtain what you would expect. In Python 2.x:

import traceback

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_exc()

...will display the traceback of the last exception:

Traceback (most recent call last):
  File "e.py", line 7, in <module>
    raise TypeError("Again !?!")
TypeError: Again !?!

If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info in a local variable and display it using print_exception:

import traceback
import sys

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        exc_info = sys.exc_info()

        # do you usefull stuff here
        # (potentially raising an exception)
        try:
            raise TypeError("Again !?!")
        except:
            pass
        # end of useful stuff


    finally:
        # Display the *original* exception
        traceback.print_exception(*exc_info)
        del exc_info

Producing:

Traceback (most recent call last):
  File "t.py", line 6, in <module>
    raise TypeError("Oups!")
TypeError: Oups!

Few pitfalls with this though:

  • From the doc of sys_info:

    Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)

  • but, from the same doc:

    Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.


On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:

import traceback

try:
    raise TypeError("Oups!")
except Exception as err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_tb(err.__traceback__)

... will display:

  File "e3.py", line 4, in <module>
    raise TypeError("Oups!")
🌐
Python.org
discuss.python.org › python help
How to get the error line? - Python Help - Discussions on Python.org
February 9, 2024 - I want to ask in general when I execute small code from the terminal I get the error but I dont know which line cause this error so how I know which line ? Thanks
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
These exceptions can be handled using the try statement: The try block will generate an exception, because x is not defined: try: print(x) except: print("An exception occurred") Try it Yourself »
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file.
🌐
Honeybadger
honeybadger.io › blog › a-guide-to-exception-handling-in-python
The ultimate guide to Python exception handling - Honeybadger Developer Blog
March 28, 2025 - Instead of crashing, your code can log the error, show a user-friendly message, or even use some predetermined fallback logic. This makes exception handling essential for writing robust applications that can withstand a wide range of real-world scenarios. Here’s an example of a ZeroDivisionError exception being raised and handled using a try-except block: try: result = 10 / 0 # Raises ZeroDivisionError except ZeroDivisionError: print("Error: Division by zero!")