🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 169 (from laksa098)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

📄
INDEXABLE
CRAWLED
5 months ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH5.4 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://stackoverflow.com/questions/4690600/python-exception-message-capturing
Last Crawled2025-10-31 21:55:54 (5 months ago)
First Indexed2017-04-26 17:56:26 (8 years ago)
HTTP Status Code200
Meta Titlepython exception message capturing - Stack Overflow
Meta Descriptionnull
Meta Canonicalnull
Boilerpipe Text
If you want the error class, error message, and stack trace, use sys.exc_info() . Minimal working code with some formatting: import sys import traceback try : ans = 1 / 0 except BaseException as ex: ex_type, ex_value, ex_traceback = sys.exc_info() trace_back = traceback.extract_tb(ex_traceback) stack_trace = list () for trace in trace_back: stack_trace.append( "File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[ 0 ], trace[ 1 ], trace[ 2 ], trace[ 3 ])) print ( "Exception type : %s " % ex_type.__name__) print ( "Exception message : %s" %ex_value) print ( "Stack trace : %s" %stack_trace) Which gives the following output: Exception type : ZeroDivisionError Exception message : division by zero Stack trace : [ 'File : .\\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0' ] The function sys.exc_info() gives you details about the most recent exception. It returns a tuple of (type, value, traceback) . traceback is an instance of traceback object. You can format the trace with the methods provided. More can be found in the traceback documentation .
Markdown
# ![site logo](https://stackoverflow.com/Content/Img/SE-logo75.png) By clicking “Sign up”, you agree to our [terms of service](https://stackoverflow.com/legal/terms-of-service/public) and acknowledge you have read our [privacy policy](https://stackoverflow.com/legal/privacy-policy). # OR Already have an account? [Log in](https://stackoverflow.com/users/login) [Skip to main content](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#content) [Stack Overflow](https://stackoverflow.com/) 1. [About](https://stackoverflow.co/) 2. Products 3. [For Teams](https://stackoverflow.co/teams/) 1. [Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-for-teams) 2. [Advertising Reach devs & technologists worldwide about your product, service or employer brand](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=stack-overflow-advertising) 3. [Knowledge Solutions Data licensing offering for businesses to build and improve AI tools and models](https://stackoverflow.co/api-solutions/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=overflow-api) 4. [Labs The future of collective knowledge sharing](https://stackoverflow.co/labs/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=labs) 5. [About the company](https://stackoverflow.co/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=about-the-company) [Visit the blog](https://stackoverflow.blog/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=top-nav&utm_content=blog) 1. ### [current community](https://stackoverflow.com/) - [Stack Overflow](https://stackoverflow.com/) [help](https://stackoverflow.com/help) [chat](https://chat.stackoverflow.com/?tab=explore) - [Meta Stack Overflow](https://meta.stackoverflow.com/) ### your communities [Sign up](https://stackoverflow.com/users/signup?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F4690600%2Fpython-exception-message-capturing) or [log in](https://stackoverflow.com/users/login?ssrc=site_switcher&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F4690600%2Fpython-exception-message-capturing) to customize your list. ### [more stack exchange communities](https://stackexchange.com/sites) [company blog](https://stackoverflow.blog/) 2. [Log in](https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F4690600%2Fpython-exception-message-capturing) 3. [Sign up](https://stackoverflow.com/users/signup?ssrc=head&returnurl=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F4690600%2Fpython-exception-message-capturing) # Let's set up your homepage Select a few topics you're interested in: python javascript c\# reactjs java android html flutter c++ node.js typescript css r php angular next.js spring-boot machine-learning sql excel ios azure docker Or search from our full list: - javascript - python - java - c\# - php - android - html - jquery - c++ - css - ios - sql - mysql - r - reactjs - node.js - arrays - c - asp.net - json - python-3.x - .net - ruby-on-rails - sql-server - swift - django - angular - objective-c - excel - pandas - angularjs - regex - typescript - ruby - linux - ajax - iphone - vba - xml - laravel - spring - asp.net-mvc - database - wordpress - string - flutter - postgresql - mongodb - wpf - windows - xcode - amazon-web-services - bash - git - oracle-database - spring-boot - dataframe - azure - firebase - list - multithreading - docker - vb.net - react-native - eclipse - algorithm - powershell - macos - visual-studio - numpy - image - forms - scala - function - vue.js - performance - twitter-bootstrap - selenium - winforms - kotlin - loops - express - dart - hibernate - sqlite - matlab - python-2.7 - shell - rest - apache - entity-framework - android-studio - csv - maven - linq - qt - dictionary - unit-testing - asp.net-core - facebook - apache-spark - tensorflow - file - swing - class - unity-game-engine - sorting - date - authentication - go - symfony - t-sql - opencv - matplotlib - .htaccess - google-chrome - for-loop - datetime - codeigniter - perl - http - validation - sockets - google-maps - object - uitableview - xaml - oop - visual-studio-code - if-statement - cordova - ubuntu - web-services - email - android-layout - github - spring-mvc - elasticsearch - kubernetes - selenium-webdriver - ms-access - ggplot2 - user-interface - parsing - pointers - c++11 - google-sheets - security - machine-learning - google-apps-script - ruby-on-rails-3 - templates - flask - nginx - variables - exception - sql-server-2008 - gradle - debugging - tkinter - delphi - listview - jpa - asynchronous - web-scraping - haskell - pdf - jsp - ssl - amazon-s3 - google-cloud-platform - jenkins - testing - xamarin - wcf - batch-file - generics - npm - ionic-framework - network-programming - unix - recursion - google-app-engine - mongoose - visual-studio-2010 - .net-core - android-fragments - assembly - animation - math - svg - session - rust - intellij-idea - hadoop - curl - join - next.js - winapi - django-models - laravel-5 - url - heroku - http-redirect - tomcat - google-cloud-firestore - inheritance - webpack - image-processing - gcc - keras - swiftui - asp.net-mvc-4 - logging - dom - matrix - pyspark - actionscript-3 - button - post - optimization - firebase-realtime-database - web - jquery-ui - cocoa - xpath - iis - d3.js - javafx - firefox - xslt - internet-explorer - caching - select - asp.net-mvc-3 - opengl - events - asp.net-web-api - plot - dplyr - encryption - magento - stored-procedures - search - amazon-ec2 - ruby-on-rails-4 - memory - canvas - audio - multidimensional-array - random - jsf - vector - redux - cookies - input - facebook-graph-api - flash - indexing - xamarin.forms - arraylist - ipad - cocoa-touch - data-structures - video - azure-devops - model-view-controller - serialization - apache-kafka - jdbc - woocommerce - razor - routes - awk - servlets - mod-rewrite - excel-formula - beautifulsoup - filter - docker-compose - iframe - aws-lambda - design-patterns - text - visual-c++ - django-rest-framework - cakephp - mobile - android-intent - struct - react-hooks - methods - groovy - mvvm - ssh - lambda - checkbox - time - ecmascript-6 - grails - google-chrome-extension - installation - cmake - sharepoint - shiny - spring-security - jakarta-ee - plsql - android-recyclerview - core-data - types - sed - meteor - android-activity - activerecord - bootstrap-4 - websocket - graph - replace - group-by - scikit-learn - vim - file-upload - junit - boost - memory-management - sass - import - async-await - deep-learning - error-handling - eloquent - dynamic - soap - dependency-injection - silverlight - layout - apache-spark-sql - charts - deployment - browser - gridview - svn - while-loop - google-bigquery - vuejs2 - highcharts - dll - ffmpeg - view - foreach - makefile - plugins - redis - c\#-4.0 - reporting-services - jupyter-notebook - unicode - merge - reflection - https - server - google-maps-api-3 - twitter - oauth-2.0 - extjs - terminal - axios - pip - split - cmd - pytorch - encoding - django-views - collections - database-design - hash - netbeans - automation - data-binding - ember.js - build - tcp - pdo - sqlalchemy - apache-flex - mysqli - entity-framework-core - concurrency - command-line - spring-data-jpa - printing - react-redux - java-8 - lua - html-table - ansible - neo4j - jestjs - service - parameters - material-ui - enums - flexbox - module - promise - visual-studio-2012 - outlook - firebase-authentication - web-applications - webview - uwp - jquery-mobile - utf-8 - datatable - python-requests - parallel-processing - colors - drop-down-menu - scipy - scroll - tfs - hive - count - syntax - ms-word - twitter-bootstrap-3 - ssis - fonts - rxjs - constructor - google-analytics - file-io - three.js - paypal - powerbi - graphql - cassandra - discord - graphics - compiler-errors - gwt - socket.io - react-router - solr - backbone.js - url-rewriting - memory-leaks - datatables - nlp - terraform - oauth - datagridview - drupal - zend-framework - oracle11g - knockout.js - triggers - neural-network - interface - django-forms - angular-material - casting - jmeter - google-api - linked-list - path - timer - arduino - django-templates - proxy - orm - directory - windows-phone-7 - parse-platform - visual-studio-2015 - cron - conditional-statements - push-notification - functional-programming - primefaces - pagination - model - jar - xamarin.android - hyperlink - uiview - visual-studio-2013 - vbscript - google-cloud-functions - gitlab - azure-active-directory - jwt - download - swift3 - sql-server-2005 - process - configuration - rspec - pygame - properties - combobox - callback - windows-phone-8 - linux-kernel - safari - scrapy - permissions - emacs - clojure - scripting - x86 - raspberry-pi - scope - io - expo - azure-functions - compilation - responsive-design - mongodb-query - nhibernate - angularjs-directive - request - bluetooth - reference - binding - dns - architecture - 3d - playframework - pyqt - version-control - discord.js - doctrine-orm - package - f\# - rubygems - get - sql-server-2012 - autocomplete - tree - openssl - datepicker - kendo-ui - jackson - yii - controller - grep - nested - xamarin.ios - static - null - statistics - transactions - datagrid - active-directory - dockerfile - uiviewcontroller - webforms - discord.py - sas - phpmyadmin - computer-vision - notifications - duplicates - mocking - pycharm - youtube - yaml - nullpointerexception - menu - blazor - sum - plotly - bitmap - asp.net-mvc-5 - visual-studio-2008 - yii2 - floating-point - electron - css-selectors - stl - jsf-2 - android-listview - time-series - cryptography - ant - hashmap - character-encoding - stream - msbuild - asp.net-core-mvc - sdk - google-drive-api - jboss - selenium-chromedriver - joomla - devise - cors - navigation - anaconda - cuda - background - frontend - multiprocessing - binary - pyqt5 - camera - iterator - linq-to-sql - mariadb - onclick - android-jetpack-compose - ios7 - microsoft-graph-api - rabbitmq - android-asynctask - tabs - laravel-4 - amazon-dynamodb - environment-variables - insert - uicollectionview - linker - xsd - coldfusion - console - continuous-integration - upload - textview - ftp - opengl-es - macros - operating-system - mockito - localization - formatting - xml-parsing - vuejs3 - json.net - type-conversion - data.table - kivy - timestamp - integer - calendar - segmentation-fault - android-ndk - prolog - drag-and-drop - char - crash - jasmine - automated-tests - dependencies - geometry - azure-pipelines - android-gradle-plugin - fortran - itext - sprite-kit - mfc - header - firebase-cloud-messaging - attributes - nosql - format - nuxt.js - odoo - db2 - jquery-plugins - event-handling - jenkins-pipeline - julia - leaflet - nestjs - annotations - flutter-layout - keyboard - postman - textbox - arm - visual-studio-2017 - stripe-payments - gulp - libgdx - synchronization - timezone - azure-web-app-service - uikit - dom-events - xampp - wso2 - crystal-reports - swagger - namespaces - aggregation-framework - android-emulator - uiscrollview - jvm - google-sheets-formula - sequelize.js - chart.js - com - snowflake-cloud-data-platform - subprocess - geolocation - webdriver - html5-canvas - centos - garbage-collection - dialog - sql-update - widget - numbers - concatenation - qml - tuples - set - java-stream - mapreduce - ionic2 - smtp - windows-10 - android-edittext - rotation - modal-dialog - spring-data - nuget - doctrine - radio-button - http-headers - grid - sonarqube - lucene - xmlhttprequest - listbox - switch-statement - initialization - internationalization - components - boolean - apache-camel - google-play - serial-port - gdb - ios5 - ldap - return - youtube-api - pivot - eclipse-plugin - latex - frameworks - tags - containers - github-actions - c++17 - subquery - dataset - asp-classic - foreign-keys - label - embedded - uinavigationcontroller - copy - delegates - struts2 - google-cloud-storage - migration - protractor - base64 - queue - find - uibutton - sql-server-2008-r2 - arguments - composer-php - append - jaxb - stack - tailwind-css - zip - cucumber - autolayout - ide - entity-framework-6 - iteration - popup - r-markdown - windows-7 - airflow - vb6 - g++ - ssl-certificate - hover - clang - jqgrid - range - gmail Next You’ll be prompted to create an account to view your personalized homepage. 1. 1. [Home](https://stackoverflow.com/) 2. [Questions](https://stackoverflow.com/questions) 3. [AI Assist Labs](https://stackoverflow.ai/) 4. [Tags](https://stackoverflow.com/tags) 5. [Challenges](https://stackoverflow.com/beta/challenges) 6. [Chat](https://chat.stackoverflow.com/rooms/259507/stack-overflow-lobby) 7. [Articles](https://stackoverflow.blog/contributed?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=so-blog&utm_content=experiment-articles) 8. [Users](https://stackoverflow.com/users) 9. [Companies](https://stackoverflow.com/jobs/companies?so_medium=stackoverflow&so_source=SiteNav) 10. [Collectives]() 11. Communities for your favorite technologies. [Explore all Collectives](https://stackoverflow.com/collectives-all) 2. Teams ![](https://cdn.sstatic.net/Img/teams/teams-promo.svg?v=e507948b81bf) Ask questions, find answers and collaborate at work with Stack Overflow for Teams. [Try Teams for free](https://stackoverflowteams.com/teams/create/free/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams) [Explore Teams](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams) 3. [Teams]() 4. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. [Explore Teams](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=side-bar&utm_content=explore-teams-compact) ##### Collectives™ on Stack Overflow Find centralized, trusted content and collaborate around the technologies you use most. [Learn more about Collectives](https://stackoverflow.com/collectives) **Teams** Q\&A for work Connect and share knowledge within a single location that is structured and easy to search. [Learn more about Teams](https://stackoverflow.co/teams/) # ![Illustration of upvote icon after it is clicked](https://cdn.sstatic.net/Img/modal/img-upvote.png?v=fce73bd9724d) # Hang on, you can't upvote just yet. You'll need to complete a few actions and gain 15 reputation points before being able to upvote. **Upvoting** indicates when questions and answers are useful. [What's reputation and how do I get it?](https://stackoverflow.com/help/whats-reputation) Instead, you can save this post to reference later. Save this post for later Not now # ![Illustration of upvote icon after it is clicked](https://cdn.sstatic.net/Img/modal/img-free-votes.png?v=1c5aa3dac50b) # Thanks for your vote! You now have 5 free votes weekly. Free votes - count toward the total vote score - does not give reputation to the author Continue to help good content that is interesting, well-researched, and useful, rise to the top! To gain full voting privileges, [earn reputation](https://stackoverflow.com/help/whats-reputation). Got it\! Go to help center to learn more # [python exception message capturing](https://stackoverflow.com/questions/4690600/python-exception-message-capturing) [Ask Question](https://stackoverflow.com/questions/ask) Asked 14 years, 9 months ago Modified [3 months ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing?lastactivity "2025-06-14 10:52:22Z") Viewed 1.6m times This question shows research effort; it is useful and clear 970 Save this question. Show activity on this post. ``` import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) FTPADDR = "some ftp address" def upload_to_ftp(con, filepath): try: f = open(filepath,'rb') # file to send con.storbinary('STOR '+ filepath, f) # Send the file f.close() # Close file and FTP logger.info('File successfully uploaded to '+ FTPADDR) except, e: logger.error('Failed to upload to ftp: '+ str(e)) ``` This doesn't seem to work, I get syntax error, what is the proper way of doing this for logging all kind of exceptions to a file - [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'") - [exception](https://stackoverflow.com/questions/tagged/exception "show questions tagged 'exception'") - [logging](https://stackoverflow.com/questions/tagged/logging "show questions tagged 'logging'") - [except](https://stackoverflow.com/questions/tagged/except "show questions tagged 'except'") - [python-logging](https://stackoverflow.com/questions/tagged/python-logging "show questions tagged 'python-logging'") [Share](https://stackoverflow.com/q/4690600 "Short permalink to this question") Share a link to this question Copy link [CC BY-SA 2.5](https://creativecommons.org/licenses/by-sa/2.5/ "The current license for this post: CC BY-SA 2.5") [Improve this question](https://stackoverflow.com/posts/4690600/edit) Follow Follow this question to receive notifications [edited Mar 24, 2023 at 8:20](https://stackoverflow.com/posts/4690600/revisions "show all edits to this post") [![vvvvv's user avatar](https://i.sstatic.net/fzsuf.jpg?s=64)](https://stackoverflow.com/users/5446749/vvvvv) [vvvvv](https://stackoverflow.com/users/5446749/vvvvv) 32\.8k1919 gold badges6969 silver badges103103 bronze badges asked Jan 14, 2011 at 11:33 [![Hellnar's user avatar](https://www.gravatar.com/avatar/eb149575d3dcbd3aca84cc4d9d689474?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/151937/hellnar) [Hellnar](https://stackoverflow.com/users/151937/hellnar)Hellnar 65\.4k8282 gold badges209209 silver badges282282 bronze badges 5 - 3 Your indentation is broken. And omit the `,` after `except`. Sven Marnach – [Sven Marnach](https://stackoverflow.com/users/279627/sven-marnach "607,086 reputation") 2011-01-14 11:35:23 +00:00 [Commented Jan 14, 2011 at 11:35](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment5173725_4690600) - 4 @SvenMarnach, if you omit the `,` after `except`, you'll get `global name 'e' is not defined`, which is not much better than wrong syntax. Val – [Val](https://stackoverflow.com/users/1083704/val "11,217 reputation") 2013-11-18 11:11:13 +00:00 [Commented Nov 18, 2013 at 11:11](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment29855594_4690600) - 22 @Val: Should be `except Exception as e` or `except Exception, e`, depending on Python version. Sven Marnach – [Sven Marnach](https://stackoverflow.com/users/279627/sven-marnach "607,086 reputation") 2013-11-19 13:03:34 +00:00 [Commented Nov 19, 2013 at 13:03](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment29900067_4690600) - 1 Probably it's somewhere around those 8 answers, but when you open a file, close part should never be inside the try statement, but either in a finally statement or wrapped by a with statement. user4396006 – user4396006 2018-08-24 17:13:39 +00:00 [Commented Aug 24, 2018 at 17:13](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment90968641_4690600) - You can do it like UnitTests in requests package do [fixexception.com/requests/expected-exception](https://fixexception.com/requests/expected-exception/) Ivan Borshchov – [Ivan Borshchov](https://stackoverflow.com/users/3479125/ivan-borshchov "3,667 reputation") 2021-06-03 07:37:24 +00:00 [Commented Jun 3, 2021 at 7:37](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment119869695_4690600) [Add a comment](https://stackoverflow.com/questions/4690600/python-exception-message-capturing "Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.") \| ## 16 Answers 16 Sorted by: [Reset to default](https://stackoverflow.com/questions/4690600/python-exception-message-capturing?answertab=scoredesc#tab-top) This answer is useful 1282 Save this answer. Show activity on this post. 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)) ``` [Share](https://stackoverflow.com/a/4690655 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/4690655/edit) Follow Follow this answer to receive notifications [edited Feb 20, 2024 at 6:07](https://stackoverflow.com/posts/4690655/revisions "show all edits to this post") [![akki's user avatar](https://www.gravatar.com/avatar/79fa9987d90325f3ab1f8c8c0f6d7565?s=64&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/3061686/akki) [akki](https://stackoverflow.com/users/3061686/akki) 2,34222 gold badges2626 silver badges3939 bronze badges answered Jan 14, 2011 at 11:40 [![eumiro's user avatar](https://www.gravatar.com/avatar/b52c27e86c87d931e654d6a2d2cdf974?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/449449/eumiro) [eumiro](https://stackoverflow.com/users/449449/eumiro)eumiro 214k3636 gold badges306306 silver badges263263 bronze badges Sign up to request clarification or add additional context in comments. ## 7 Comments Add a comment [![](https://i.sstatic.net/Urpin.jpg?s=64)](https://stackoverflow.com/users/3406170/whitebeard) whitebeard [whitebeard](https://stackoverflow.com/users/3406170/whitebeard) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment64726919_4690655) repr(e) gives you the exception(and the message string); str(e) only gives the message string. 2016-07-30T11:28:13.283Z+00:00 295 Reply - Copy link [![](https://www.gravatar.com/avatar/294c632c8748e7051c87b8961bc4f87e?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/4973698/mbdevpl) mbdevpl [mbdevpl](https://stackoverflow.com/users/4973698/mbdevpl) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment65828373_4690655) As an alternative for logging exception you could use `logger.exception(e)` instead. It will log the exception with traceback at the same `logging.ERROR` level. 2016-08-31T09:50:18.497Z+00:00 23 Reply - Copy link [![](https://i.sstatic.net/2B6rV.png?s=64)](https://stackoverflow.com/users/1601580/charlie-parker) Charlie Parker [Charlie Parker](https://stackoverflow.com/users/1601580/charlie-parker) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment81043343_4690655) `except Exception, e:` throws a Syntax error to me in python 3. Is this expected? 2017-11-01T04:12:47.11Z+00:00 10 Reply - Copy link [![](https://www.gravatar.com/avatar/b52c27e86c87d931e654d6a2d2cdf974?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/449449/eumiro) eumiro [eumiro](https://stackoverflow.com/users/449449/eumiro) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment81044650_4690655) @CharlieParker in Python3 write `except Exception as e:` 2017-11-01T05:38:42.383Z+00:00 38 Reply - Copy link [![](https://www.gravatar.com/avatar/df0d058549971acf574f2108e988d04f?s=48&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/7517192/alex) Alex [Alex](https://stackoverflow.com/users/7517192/alex) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment115644401_4690655) This is a bit misleading in 2020 because nobody has a Python version anymore that would require your first way (nobody uses Python \<2.7), yet your answer makes this seem like the default way to go in Python 2, even though the second way is virtually always better. You should just remove the first way and thereby make the answer clearer. 2020-12-22T15:23:06.177Z+00:00 4 Reply - Copy link Add a comment \| Show 2 more comments This answer is useful 403 Save this answer. Show activity on this post. The syntax `except, e:` is no longer supported in python 3. Use the following instead. ``` try: do_something() except BaseException as e: logger.error('Failed to do something: %s', str(e)) ``` [Share](https://stackoverflow.com/a/14529489 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/14529489/edit) Follow Follow this answer to receive notifications [edited Jun 14 at 10:52](https://stackoverflow.com/posts/14529489/revisions "show all edits to this post") [![Marco Sulla's user avatar](https://i.sstatic.net/uZ8dA.gif?s=64)](https://stackoverflow.com/users/1763602/marco-sulla) [Marco Sulla](https://stackoverflow.com/users/1763602/marco-sulla) 16k1414 gold badges7272 silver badges109109 bronze badges answered Jan 25, 2013 at 20:02 [![sjtaheri's user avatar](https://www.gravatar.com/avatar/21ca31729513679a6123f14abbc11814?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/958636/sjtaheri) [sjtaheri](https://stackoverflow.com/users/958636/sjtaheri)sjtaheri 4,64733 gold badges2222 silver badges1515 bronze badges ## 8 Comments Add a comment [![](https://www.gravatar.com/avatar/6f3c10c61aaadfb82851ce2c47c0f663?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/1644561/avyfain) avyfain [avyfain](https://stackoverflow.com/users/1644561/avyfain) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment58913973_14529489) Actually, you should use logger.error('Failed to do something: %s', str(e)) That way, if your logger level is above error it doesn't do the string interpolation. 2016-02-24T23:19:25.153Z+00:00 3 Reply - Copy link user1898811 user1898811 [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment64051673_14529489) @avyfain - You are incorrect. The statement `logging.error('foo %s', str(e))` will always convert `e` to a string. To achieve what you are afterm you would use `logging.error('foo %s', e)` - thereby allowing the logging framework to do (or not do) the conversion. 2016-07-11T23:29:03.627Z+00:00 12 Reply - Copy link [![](https://www.gravatar.com/avatar/294c632c8748e7051c87b8961bc4f87e?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/4973698/mbdevpl) mbdevpl [mbdevpl](https://stackoverflow.com/users/4973698/mbdevpl) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment65828406_14529489) As an alternative for logging exception you could use `logger.exception(e)` instead. It will log the exception with traceback at the same `logging.ERROR` level. 2016-08-31T09:51:02.817Z+00:00 4 Reply - Copy link [![](https://www.gravatar.com/avatar/a0635ccd3a14b9c2801ccb180ee78abe?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/1905506/roy) Roy [Roy](https://stackoverflow.com/users/1905506/roy) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment85530426_14529489) I think he/she meant "except Exception, e:" 2018-03-13T18:34:44.353Z+00:00 2 Reply - Copy link [![](https://lh4.googleusercontent.com/-YxVDude9eeE/AAAAAAAAAAI/AAAAAAAABTM/i60VX3LXLQQ/s48-rj/photo.jpg)](https://stackoverflow.com/users/7470925/jeannej) jeannej [jeannej](https://stackoverflow.com/users/7470925/jeannej) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment88835998_14529489) Beware that `except BaseException` and `except Exception` are not on the same level. `except Exception` does 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](https://docs.python.org/3/library/exceptions.html#exception-hierarchy) for the hierarchy of exceptions. 2018-06-18T21:52:36.5Z+00:00 21 Reply - Copy link Add a comment \| Show 3 more comments This answer is useful 104 Save this answer. Show activity on this post. If you want the error class, error message, and stack trace, use **`sys.exc_info()`**. Minimal working code with some formatting: ``` import sys import traceback try: ans = 1/0 except BaseException as ex: # Get current system exception ex_type, ex_value, ex_traceback = sys.exc_info() # Extract unformatter stack traces as tuples trace_back = traceback.extract_tb(ex_traceback) # Format stacktrace stack_trace = list() for trace in trace_back: stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3])) print("Exception type : %s " % ex_type.__name__) print("Exception message : %s" %ex_value) print("Stack trace : %s" %stack_trace) ``` Which gives the following output: ``` Exception type : ZeroDivisionError Exception message : division by zero Stack trace : ['File : .\\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0'] ``` The function **[sys.exc\_info()](https://docs.python.org/3.6/library/sys.html#sys.exc_info)** gives you details about the most recent exception. It returns a tuple of `(type, value, traceback)`. `traceback` is an instance of traceback object. You can format the trace with the methods provided. More can be found in the [traceback documentation](https://docs.python.org/3.6/library/traceback.html) . [Share](https://stackoverflow.com/a/49613561 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/49613561/edit) Follow Follow this answer to receive notifications [edited Aug 18, 2020 at 1:09](https://stackoverflow.com/posts/49613561/revisions "show all edits to this post") [![ziedaniel1's user avatar](https://www.gravatar.com/avatar/3c5f722459435619bf3d6ea4d19af66c?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/248522/ziedaniel1) [ziedaniel1](https://stackoverflow.com/users/248522/ziedaniel1) 36011 silver badge99 bronze badges answered Apr 2, 2018 at 14:55 [![Kavindu Dodanduwa's user avatar](https://i.sstatic.net/nSxMo0VP.jpg?s=64)](https://stackoverflow.com/users/3197055/kavindu-dodanduwa) [Kavindu Dodanduwa](https://stackoverflow.com/users/3197055/kavindu-dodanduwa)Kavindu Dodanduwa 13\.2k44 gold badges3838 silver badges4949 bronze badges ## 3 Comments Add a comment [![](https://www.gravatar.com/avatar/8bbc94977312d285045b2412257b6cb8?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/55075/kenorb) kenorb [kenorb](https://stackoverflow.com/users/55075/kenorb) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment88732934_49613561) Using `e.__class__.__name__` can return the exception class as well. 2018-06-14T20:13:48.93Z+00:00 6 Reply - Copy link [![](https://i.sstatic.net/301nx.png?s=64)](https://stackoverflow.com/users/9330812/madhatter) MadHatter [MadHatter](https://stackoverflow.com/users/9330812/madhatter) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment129501915_49613561) Thanks for the info, finally decide to use `self.logger.info("{} - {}".format(type(error).__name__, str(error)))`, works like a charm. 2022-08-12T07:25:49.557Z+00:00 1 Reply - Copy link [![](https://www.gravatar.com/avatar/65567f5e847c6761b1fe382937258466?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/849669/somebody) Somebody [Somebody](https://stackoverflow.com/users/849669/somebody) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment136481033_49613561) woah, what a mess... so much work to just get error stack trace... 2023-11-03T13:02:47.99Z+00:00 2 Reply - Copy link Add a comment This answer is useful 71 Save this answer. Show activity on this post. There are some cases where you can use the **e.message** or **e.messages**.. But it does not work in all cases. Anyway the more safe is to use the **str(e)** ``` try: ... except Exception as e: print(e.message) ``` [Share](https://stackoverflow.com/a/43453668 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://stackoverflow.com/posts/43453668/edit) Follow Follow this answer to receive notifications [edited Apr 2, 2018 at 9:11](https://stackoverflow.com/posts/43453668/revisions "show all edits to this post") answered Apr 17, 2017 at 14:43 [![Slipstream's user avatar](https://i.sstatic.net/I4Nbj.jpg?s=64)](https://stackoverflow.com/users/1866389/slipstream) [Slipstream](https://stackoverflow.com/users/1866389/slipstream)Slipstream 15\.1k44 gold badges6161 silver badges4747 bronze badges ## 3 Comments Add a comment [![](https://www.gravatar.com/avatar/b51b021fec2ca6f8eb22c629907ee2a8?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/466011/epalm) epalm [epalm](https://stackoverflow.com/users/466011/epalm) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment74061301_43453668) The problem with this is, for example, if you `except Exception as e`, and `e` is an `IOError`, you get `e.errno`, `e.filename`, and `e.strerror`, but apparently no `e.message` (at least in Python 2.7.12). If you want to capture the error message, use `str(e)`, as in the other answers. 2017-04-19T18:28:35.28Z+00:00 67 Reply - Copy link [![](https://www.gravatar.com/avatar/529a4b8512718a449afa4889a7d9a761?s=48&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/12696307/herii) Herii [Herii](https://stackoverflow.com/users/12696307/herii) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment105561813_43453668) @epalm What if you catch the IOError before Exception? 2020-01-12T14:21:25.06Z+00:00 0 Reply - Copy link [![](https://www.gravatar.com/avatar/28ee35cd7b2ad66f0e892cf25d809669?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/6526918/hosseynjf) HosseyNJF [HosseyNJF](https://stackoverflow.com/users/6526918/hosseynjf) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment108459652_43453668) @HeribertoJuárez Why catch special cases while you can simply cast it to string? 2020-04-19T18:13:51.95Z+00:00 2 Reply - Copy link Add a comment This answer is useful 55 Save this answer. Show activity on this post. Updating this to something simpler for logger (works for both python 2 and 3). You do not need traceback module. ``` import logging logger = logging.Logger('catch_all') def catchEverythingInLog(): try: ... do something ... except Exception as e: logger.error(e, exc_info=True) ... exception handling ... ``` This is now the old way (though still works): ``` import sys, traceback def catchEverything(): try: ... some operation(s) ... except: exc_type, exc_value, exc_traceback = sys.exc_info() ... exception handling ... ``` exc\_value is the error message. [Share](https://stackoverflow.com/a/19101737 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://stackoverflow.com/posts/19101737/edit) Follow Follow this answer to receive notifications [edited Oct 30, 2016 at 22:59](https://stackoverflow.com/posts/19101737/revisions "show all edits to this post") answered Sep 30, 2013 at 18:58 [![berniey's user avatar](https://www.gravatar.com/avatar/2ff4f28cf6b7449a5a88d15042cba1b0?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/1268052/berniey) [berniey](https://stackoverflow.com/users/1268052/berniey)berniey 2,96211 gold badge2020 silver badges88 bronze badges ## 2 Comments Add a comment [![](https://www.gravatar.com/avatar/455ec540f6081646ee8a12100c5c7b38?s=48&d=identicon&r=PG&f=y&so-version=2)](https://stackoverflow.com/users/4077356/sulimmesh) sulimmesh [sulimmesh](https://stackoverflow.com/users/4077356/sulimmesh) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment60257170_19101737) This would be my preferred method. Just printing the string is useful for logging I suppose, but if I need to do anything with that information I need more than just a string. 2016-03-30T18:31:16.12Z+00:00 3 Reply - Copy link [![](https://www.gravatar.com/avatar/22361102c97f14fe158361621d811d0a?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/2369544/starikoff) starikoff [starikoff](https://stackoverflow.com/users/2369544/starikoff) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment92482043_19101737) You don't need to 'import traceback' in the second example, right? 2018-10-12T13:13:46.413Z+00:00 3 Reply - Copy link This answer is useful 27 Save this answer. Show activity on this post. Using `str(e)` or `repr(e)` to represent the exception, you won't get the actual stack trace, so it is not helpful to find where the exception is. After reading other answers and the logging package doc, the following two ways works great to print the actual stack trace for easier debugging: # use `logger.debug()` with parameter `exc_info` ``` try: # my code except SomeError as e: logger.debug(e, exc_info=True) ``` # use `logger.exception()` or we can directly use `logger.exception()` to print the exception. ``` try: # my code except SomeError as e: logger.exception(e) ``` [Share](https://stackoverflow.com/a/61441684 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/61441684/edit) Follow Follow this answer to receive notifications [edited Aug 13, 2020 at 17:55](https://stackoverflow.com/posts/61441684/revisions "show all edits to this post") [![Vikramaditya Gaonkar's user avatar](https://i.sstatic.net/jly03.jpg?s=64)](https://stackoverflow.com/users/2542835/vikramaditya-gaonkar) [Vikramaditya Gaonkar](https://stackoverflow.com/users/2542835/vikramaditya-gaonkar) 7371111 silver badges2424 bronze badges answered Apr 26, 2020 at 13:34 [![jdhao's user avatar](https://i.sstatic.net/zto2h.jpg?s=64)](https://stackoverflow.com/users/6064933/jdhao) [jdhao](https://stackoverflow.com/users/6064933/jdhao)jdhao 29\.4k2323 gold badges158158 silver badges323323 bronze badges ## Comments Add a comment This answer is useful 24 Save this answer. Show activity on this post. You can use `logger.exception("msg")` for logging exception with traceback: ``` try: #your code except Exception as e: logger.exception('Failed: ' + str(e)) ``` [Share](https://stackoverflow.com/a/28431302 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/ "The current license for this post: CC BY-SA 3.0") [Improve this answer](https://stackoverflow.com/posts/28431302/edit) Follow Follow this answer to receive notifications answered Feb 10, 2015 at 12:09 [![Peter's user avatar](https://www.gravatar.com/avatar/82f6847dddbc87f676d4aebd7a7542d4?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/1382867/peter) [Peter](https://stackoverflow.com/users/1382867/peter)Peter 61911 gold badge88 silver badges1515 bronze badges ## 2 Comments Add a comment [![](https://i.sstatic.net/jQIuY.jpg?s=64)](https://stackoverflow.com/users/699665/markhu) MarkHu [MarkHu](https://stackoverflow.com/users/699665/markhu) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment59236975_28431302) Coincidently, `e.msg` is the string representation of `Exception` class. 2016-03-03T20:54:17.887Z+00:00 0 Reply - Copy link [![](https://www.gravatar.com/avatar/294c632c8748e7051c87b8961bc4f87e?s=48&d=identicon&r=PG)](https://stackoverflow.com/users/4973698/mbdevpl) mbdevpl [mbdevpl](https://stackoverflow.com/users/4973698/mbdevpl) [Over a year ago](https://stackoverflow.com/questions/4690600/python-exception-message-capturing#comment65828456_28431302) Or simply `logger.exception(e)`. 2016-08-31T09:52:10.773Z+00:00 6 Reply - Copy link This answer is useful 21 Save this answer. Show activity on this post. After python 3.6, you can use formatted string literal. It's neat! (<https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498>) ``` try ... except Exception as e: logger.error(f"Failed to upload to ftp: {e}") ``` [Share](https://stackoverflow.com/a/52206134 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/52206134/edit) Follow Follow this answer to receive notifications answered Sep 6, 2018 at 14:16 [![Chuan Ma's user avatar](https://www.gravatar.com/avatar/b9c1eafa90f9b895aff24750f7be1cbc?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/1370036/chuan-ma) [Chuan Ma](https://stackoverflow.com/users/1370036/chuan-ma)Chuan Ma 9,91422 gold badges4949 silver badges3737 bronze badges ## Comments Add a comment This answer is useful 14 Save this answer. Show activity on this post. If you want to see the original error message, (*file* & *line number*) ``` import traceback try: print(3/0) except Exception as e: traceback.print_exc() ``` This will show you the same error message as if you didn't use `try-except`. [Share](https://stackoverflow.com/a/70377329 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/70377329/edit) Follow Follow this answer to receive notifications answered Dec 16, 2021 at 10:22 [![starriet 차주녕's user avatar](https://i.sstatic.net/WpcbD.jpg?s=64)](https://stackoverflow.com/users/10027592/starriet-%EC%B0%A8%EC%A3%BC%EB%85%95) [starriet 차주녕](https://stackoverflow.com/users/10027592/starriet-%EC%B0%A8%EC%A3%BC%EB%85%95)starriet 차주녕 4,1963333 silver badges3333 bronze badges ## Comments Add a comment This answer is useful 13 Save this answer. Show activity on this post. You can try specifying the BaseException type explicitly. However, this will only catch derivatives of BaseException. While this includes all implementation-provided exceptions, it is also possibly to raise arbitrary old-style classes. ``` try: do_something() except BaseException, e: logger.error('Failed to do something: ' + str(e)) ``` [Share](https://stackoverflow.com/a/4690647 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 2.5](https://creativecommons.org/licenses/by-sa/2.5/ "The current license for this post: CC BY-SA 2.5") [Improve this answer](https://stackoverflow.com/posts/4690647/edit) Follow Follow this answer to receive notifications answered Jan 14, 2011 at 11:40 [![Heini Høgnason's user avatar](https://www.gravatar.com/avatar/752cb65dfd817b97837b42b3cd5e71d6?s=64&d=identicon&r=PG)](https://stackoverflow.com/users/428329/heini-h%C3%B8gnason) [Heini Høgnason](https://stackoverflow.com/users/428329/heini-h%C3%B8gnason)Heini Høgnason 67744 silver badges1010 bronze badges ## Comments Add a comment This answer is useful 7 Save this answer. Show activity on this post. for the future strugglers, in python 3.8.2(and maybe a few versions before that), the syntax is ``` except Attribute as e: print(e) ``` [Share](https://stackoverflow.com/a/60793229 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/60793229/edit) Follow Follow this answer to receive notifications answered Mar 21, 2020 at 21:00 [![syter's user avatar](https://lh3.googleusercontent.com/-hm5jw7GSYQo/AAAAAAAAAAI/AAAAAAAAD9g/PICrj7hRJ4s/s64-rj/photo.jpg)](https://stackoverflow.com/users/11723929/syter) [syter](https://stackoverflow.com/users/11723929/syter)syter 14522 silver badges1111 bronze badges ## Comments Add a comment This answer is useful 7 Save this answer. Show activity on this post. There is also a way to get the raw values passed to the exception class without having to change the content type. For e.g I raise type codes with error messages in one of my frameworks. ``` try: # TODO: Your exceptional code here raise Exception((1, "Your code wants the program to exit")) except Exception as e: print("Exception Type:", e.args[0][0], "Message:", e.args[0][1]) ``` Output ``` Exception Type: 1 Message: 'Your code wants the program to exit' ``` [Share](https://stackoverflow.com/a/75269630 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/75269630/edit) Follow Follow this answer to receive notifications answered Jan 28, 2023 at 17:44 [![Illegal Operator's user avatar](https://i.sstatic.net/8G67M.jpg?s=64)](https://stackoverflow.com/users/1647394/illegal-operator) [Illegal Operator](https://stackoverflow.com/users/1647394/illegal-operator)Illegal Operator 76188 silver badges1515 bronze badges ## Comments Add a comment This answer is useful 6 Save this answer. Show activity on this post. In Python 3, `str(ex)` gives us the error message. You could use `repr(ex)` to get the full text, including the name of the exception raised. ``` arr = ["a", "b", "c"] try: print(arr[5]) except IndexError as ex: print(repr(ex)) # IndexError: list index out of range print(str(ex)) # list index out of range ``` [Share](https://stackoverflow.com/a/75228768 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/75228768/edit) Follow Follow this answer to receive notifications answered Jan 25, 2023 at 0:51 [![Tomisin Abiodun's user avatar](https://graph.facebook.com/1863404813688471/picture?type=large)](https://stackoverflow.com/users/8921643/tomisin-abiodun) [Tomisin Abiodun](https://stackoverflow.com/users/8921643/tomisin-abiodun)Tomisin Abiodun 12144 silver badges44 bronze badges ## Comments Add a comment This answer is useful 5 Save this answer. Show activity on this post. Use str(ex) to print execption ``` try: #your code except ex: print(str(ex)) ``` [Share](https://stackoverflow.com/a/50584719 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/50584719/edit) Follow Follow this answer to receive notifications answered May 29, 2018 at 12:42 [![Niraj Trivedi's user avatar](https://i.sstatic.net/eq0HA.png?s=64)](https://stackoverflow.com/users/3839344/niraj-trivedi) [Niraj Trivedi](https://stackoverflow.com/users/3839344/niraj-trivedi)Niraj Trivedi 2,9402727 silver badges2727 bronze badges ## Comments Add a comment This answer is useful 0 Save this answer. Show activity on this post. There were already useful answers provided. Just a small additional hint located between proposals to use *sys.exc\_info()* and to use *traceback.print\_exc()* : There is a way to **capture easily** the original exception trace **inside the script** if saving to log-file is not needed (or before saving to file): ``` import traceback try: do_something # your code, which could cause exception except Exception as e: exception_details_list = traceback.format_exc() print(exception_details_list) # just to show the retrieved exception_details_list ``` *Note: there are also further useful functions available by [traceback](https://docs.python.org/3/library/traceback.html) (e.g. to capture only limited information about exception).* [Share](https://stackoverflow.com/a/79295002 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/79295002/edit) Follow Follow this answer to receive notifications answered Dec 19, 2024 at 16:37 [![Dr.CKYHC's user avatar](https://lh4.googleusercontent.com/-kWEDFCqdPhw/AAAAAAAAAAI/AAAAAAAAAAA/AMZuuclFrD9o5RJ9jFimfTGGmEVDPoYmYw/s96-c/s64-rj/photo.jpg)](https://stackoverflow.com/users/19041857/dr-ckyhc) [Dr.CKYHC](https://stackoverflow.com/users/19041857/dr-ckyhc)Dr.CKYHC 10555 bronze badges ## Comments Add a comment This answer is useful \-1 Save this answer. Show activity on this post. The easiest way to do this is available through the [Polog](https://github.com/pomponchik/polog) library. Import it: ``` $ pip install polog ``` And use: ``` from polog import log, config, file_writer config.add_handlers(file_writer('file.log')) with log('message').suppress(): do_something() ``` Note how much less space the code has taken up vertically: only 2 lines. [Share](https://stackoverflow.com/a/74210713 "Short permalink to this answer") Share a link to this answer Copy link [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/ "The current license for this post: CC BY-SA 4.0") [Improve this answer](https://stackoverflow.com/posts/74210713/edit) Follow Follow this answer to receive notifications answered Oct 26, 2022 at 15:51 [![Evgeniy Blinov's user avatar](https://lh3.googleusercontent.com/a-/AOh14GiTorduX2qPJYDBrrs4dbMsPj5XKJZp-aqInCLHTA=k-s64)](https://stackoverflow.com/users/14522393/evgeniy-blinov) [Evgeniy Blinov](https://stackoverflow.com/users/14522393/evgeniy-blinov)Evgeniy Blinov 40744 silver badges33 bronze badges ## Comments Add a comment **[Protected question](https://stackoverflow.com/help/privileges/protect-questions)**. To answer this question, you need to have at least 10 reputation on this site (not counting the [association bonus](https://meta.stackexchange.com/questions/141648/what-is-the-association-bonus-and-how-does-it-work)). The reputation requirement helps protect this question from spam and non-answer activity. Start asking to get answers Find the answer to your question by asking. [Ask question](https://stackoverflow.com/questions/ask) Explore related questions - [python](https://stackoverflow.com/questions/tagged/python "show questions tagged 'python'") - [exception](https://stackoverflow.com/questions/tagged/exception "show questions tagged 'exception'") - [logging](https://stackoverflow.com/questions/tagged/logging "show questions tagged 'logging'") - [except](https://stackoverflow.com/questions/tagged/except "show questions tagged 'except'") - [python-logging](https://stackoverflow.com/questions/tagged/python-logging "show questions tagged 'python-logging'") See similar questions with these tags. - The Overflow Blog - [Who watches the watchers? LLM on LLM evaluations](https://stackoverflow.blog/2025/10/09/who-watches-the-watchers-llm-on-llm-evaluations/?cb=1) - [Vite is like the United Nations of JavaScript](https://stackoverflow.blog/2025/10/10/vite-is-like-the-united-nations-of-javascript/?cb=1) - Featured on Meta - [Please welcome V2Blast back to the Community Team\!](https://meta.stackexchange.com/questions/412987/please-welcome-v2blast-back-to-the-community-team?cb=1) - [A First Look: Stack Overflow Redesign](https://meta.stackexchange.com/questions/412992/a-first-look-stack-overflow-redesign?cb=1) - [Policy: Generative AI (e.g., ChatGPT) is banned](https://meta.stackoverflow.com/questions/421831/policy-generative-ai-e-g-chatgpt-is-banned?cb=1) - [Exploring new types of questions on Stack Overflow](https://meta.stackoverflow.com/questions/435121/exploring-new-types-of-questions-on-stack-overflow?cb=1) Community activity Last 1 hr - Users online activity 7290 users online - 13 questions - 22 answers - 56 comments - 159 upvotes Popular tags [php](https://stackoverflow.com/questions/tagged/php)[javascript](https://stackoverflow.com/questions/tagged/javascript)[android](https://stackoverflow.com/questions/tagged/android)[python](https://stackoverflow.com/questions/tagged/python)[database](https://stackoverflow.com/questions/tagged/database)[c++](https://stackoverflow.com/questions/tagged/c++) #### Linked [\-1](https://stackoverflow.com/questions/68964275/how-to-check-what-message-inside-of-an-exception?lq=1 "Question score (upvotes - downvotes)") [How to check what message inside of an exception](https://stackoverflow.com/questions/68964275/how-to-check-what-message-inside-of-an-exception?noredirect=1&lq=1) [10](https://stackoverflow.com/questions/33237866/django-add-custom-form-errors-to-form-errors?lq=1 "Question score (upvotes - downvotes)") [Django add custom form errors to form.errors](https://stackoverflow.com/questions/33237866/django-add-custom-form-errors-to-form-errors?noredirect=1&lq=1) [3](https://stackoverflow.com/questions/45131565/how-to-print-an-exception?lq=1 "Question score (upvotes - downvotes)") [How to print an exception?](https://stackoverflow.com/questions/45131565/how-to-print-an-exception?noredirect=1&lq=1) [1](https://stackoverflow.com/questions/71557425/selenium-python-unable-to-catch-a-timeoutexception-with-try-webdriverwait?lq=1 "Question score (upvotes - downvotes)") [Selenium + Python: Unable to catch a TimeoutException with Try & WebDriverWait](https://stackoverflow.com/questions/71557425/selenium-python-unable-to-catch-a-timeoutexception-with-try-webdriverwait?noredirect=1&lq=1) [0](https://stackoverflow.com/questions/74740099/how-do-i-return-error-in-exception-in-python?lq=1 "Question score (upvotes - downvotes)") [How do i return error in exception in python?](https://stackoverflow.com/questions/74740099/how-do-i-return-error-in-exception-in-python?noredirect=1&lq=1) [0](https://stackoverflow.com/questions/69459524/i-cant-figure-out-how-to-handle-different-errors?lq=1 "Question score (upvotes - downvotes)") [I can't figure out how to handle different errors](https://stackoverflow.com/questions/69459524/i-cant-figure-out-how-to-handle-different-errors?noredirect=1&lq=1) [\-1](https://stackoverflow.com/questions/38399040/user-defined-and-built-in-arguments-in-exceptions?lq=1 "Question score (upvotes - downvotes)") [User Defined and built in Arguments in exceptions](https://stackoverflow.com/questions/38399040/user-defined-and-built-in-arguments-in-exceptions?noredirect=1&lq=1) #### Related [5](https://stackoverflow.com/questions/1249795/convert-python-exception-information-to-string-for-logging?rq=3 "Question score (upvotes - downvotes)") [Convert Python exception information to string for logging](https://stackoverflow.com/questions/1249795/convert-python-exception-information-to-string-for-logging?rq=3) [1](https://stackoverflow.com/questions/10060840/python-selective-handling-of-exception-traceback?rq=3 "Question score (upvotes - downvotes)") [python - Selective handling of exception traceback](https://stackoverflow.com/questions/10060840/python-selective-handling-of-exception-traceback?rq=3) [0](https://stackoverflow.com/questions/23262590/python-exceptions-logging?rq=3 "Question score (upvotes - downvotes)") [Python Exceptions Logging](https://stackoverflow.com/questions/23262590/python-exceptions-logging?rq=3) [0](https://stackoverflow.com/questions/34812010/logging-custom-exceptions-python?rq=3 "Question score (upvotes - downvotes)") [Logging custom exceptions Python](https://stackoverflow.com/questions/34812010/logging-custom-exceptions-python?rq=3) [0](https://stackoverflow.com/questions/56152080/catch-an-exception-in-python-but-still-continue?rq=3 "Question score (upvotes - downvotes)") [Catch an exception in python... but still continue](https://stackoverflow.com/questions/56152080/catch-an-exception-in-python-but-still-continue?rq=3) [6](https://stackoverflow.com/questions/56932583/correct-way-logging-exception-messages-in-python?rq=3 "Question score (upvotes - downvotes)") [Correct way logging exception messages in python](https://stackoverflow.com/questions/56932583/correct-way-logging-exception-messages-in-python?rq=3) [0](https://stackoverflow.com/questions/62337507/python-exception-handling-of-logging-itself?rq=3 "Question score (upvotes - downvotes)") [Python exception handling of logging itself](https://stackoverflow.com/questions/62337507/python-exception-handling-of-logging-itself?rq=3) [1](https://stackoverflow.com/questions/62687174/logging-an-unknown-exception-in-python?rq=3 "Question score (upvotes - downvotes)") [Logging an unknown exception in Python](https://stackoverflow.com/questions/62687174/logging-an-unknown-exception-in-python?rq=3) [0](https://stackoverflow.com/questions/63498882/logging-exception-into-log-file-in-python?rq=3 "Question score (upvotes - downvotes)") [logging exception into log file in python](https://stackoverflow.com/questions/63498882/logging-exception-into-log-file-in-python?rq=3) [1](https://stackoverflow.com/questions/68098658/get-exception-type-message-as-string-in-except?rq=3 "Question score (upvotes - downvotes)") [Get Exception type + message as string in except](https://stackoverflow.com/questions/68098658/get-exception-type-message-as-string-in-except?rq=3) #### [Hot Network Questions](https://stackexchange.com/questions?tab=hot) - [Parse rpip7 musical notation](https://codegolf.stackexchange.com/questions/284074/parse-rpip7-musical-notation) - [Charles Dickens school master stating "facts, facts, facts!"](https://literature.stackexchange.com/questions/29853/charles-dickens-school-master-stating-facts-facts-facts) - [Help me understand the oddness experienced when trying to edit an SVG with free web-based tools?](https://graphicdesign.stackexchange.com/questions/169563/help-me-understand-the-oddness-experienced-when-trying-to-edit-an-svg-with-free) - [Translating "You go girl", "Get it girl" and "Girl power"](https://german.stackexchange.com/questions/81810/translating-you-go-girl-get-it-girl-and-girl-power) - [Is it possible to create a language with no paradoxical statements?](https://philosophy.stackexchange.com/questions/131040/is-it-possible-to-create-a-language-with-no-paradoxical-statements) - [How does moving through Difficult Terrain affect remaining speed when switching to a special Speed?](https://rpg.stackexchange.com/questions/216787/how-does-moving-through-difficult-terrain-affect-remaining-speed-when-switching) - [Five squares are next to each other. What is area of the shaded triangle?](https://math.stackexchange.com/questions/5101157/five-squares-are-next-to-each-other-what-is-area-of-the-shaded-triangle) - [Fluctuating results with NIntegrate](https://mathematica.stackexchange.com/questions/315637/fluctuating-results-with-nintegrate) - [How does -e work in sed?](https://unix.stackexchange.com/questions/800343/how-does-e-work-in-sed) - [How to add extra y ticks to a pgfplots axis on the right with fixed width?](https://tex.stackexchange.com/questions/752268/how-to-add-extra-y-ticks-to-a-pgfplots-axis-on-the-right-with-fixed-width) - [My Six Children](https://puzzling.stackexchange.com/questions/133539/my-six-children) - [How to communicate on my CV that I was a TA for multiple groups of students split from the same cohort?](https://academia.stackexchange.com/questions/221693/how-to-communicate-on-my-cv-that-i-was-a-ta-for-multiple-groups-of-students-spli) - [How does the bike geometry change when I use a smaller front wheel?](https://bicycles.stackexchange.com/questions/97593/how-does-the-bike-geometry-change-when-i-use-a-smaller-front-wheel) - [Ethical aspects of sending another editor the reviews as an author?](https://academia.stackexchange.com/questions/221646/ethical-aspects-of-sending-another-editor-the-reviews-as-an-author) - [With ZFC foundations, if all math objects are sets, where do these sets "live"?](https://math.stackexchange.com/questions/5100759/with-zfc-foundations-if-all-math-objects-are-sets-where-do-these-sets-live) - [Monopole or Dipole for 20 m field day with trees](https://ham.stackexchange.com/questions/23709/monopole-or-dipole-for-20-m-field-day-with-trees) - [Best formulation of Riemann hypothesis for a general audience](https://mathoverflow.net/questions/501311/best-formulation-of-riemann-hypothesis-for-a-general-audience) - [Place a nonzero digit into some of the white cells of the grid](https://puzzling.stackexchange.com/questions/133529/place-a-nonzero-digit-into-some-of-the-white-cells-of-the-grid) - [Identifying polygons with specific shape properties in QGIS](https://gis.stackexchange.com/questions/495662/identifying-polygons-with-specific-shape-properties-in-qgis) - [How would the size of animal life be affected by lower surface tension?](https://worldbuilding.stackexchange.com/questions/269403/how-would-the-size-of-animal-life-be-affected-by-lower-surface-tension) - [Why do dictionaries say that 'trip' is pronounced /trɪp/ while I can hear /tʃrɪp/?](https://linguistics.stackexchange.com/questions/51390/why-do-dictionaries-say-that-trip-is-pronounced-tr%C9%AAp-while-i-can-hear-t%CA%83r%C9%AAp) - [A referee who is likely an author of the competing study](https://academia.stackexchange.com/questions/221686/a-referee-who-is-likely-an-author-of-the-competing-study) - [How can I model a Cable Lug with a radially crushed tube end?](https://blender.stackexchange.com/questions/339543/how-can-i-model-a-cable-lug-with-a-radially-crushed-tube-end) - [Has the Nobel Peace Prize ever been awarded for trying (but not succeeding) to end conflicts?](https://politics.stackexchange.com/questions/93720/has-the-nobel-peace-prize-ever-been-awarded-for-trying-but-not-succeeding-to-e) [Question feed](https://stackoverflow.com/feeds/question/4690600 "Feed of this question and its answers") # Subscribe to RSS Question feed To subscribe to this RSS feed, copy and paste this URL into your RSS reader. ![](https://stackoverflow.com/posts/4690600/ivc/5ebc?prg=e59d8f14-ee6b-44b1-bf15-050ce84c8398) lang-py # Why are you flagging this comment? Probable spam. This comment promotes a product, service or website while [failing to disclose the author's affiliation](https://stackoverflow.com/help/promotion). Unfriendly or contains harassment/bigotry/abuse. This comment is unkind, insulting or attacks another person or group. Learn more in our [Code of Conduct](https://stackoverflow.com/conduct/abusive-behavior). Not needed. This comment is not relevant to the post. ``` ``` Enter at least 6 characters Something else. A problem not listed above. Try to be as specific as possible. ``` ``` Enter at least 6 characters Flag comment Cancel You have 0 flags left today ##### [Stack Overflow](https://stackoverflow.com/) - [Questions](https://stackoverflow.com/questions) - [Help](https://stackoverflow.com/help) - [Chat](https://chat.stackoverflow.com/?tab=explore) ##### [Products](https://stackoverflow.co/) - [Teams](https://stackoverflow.co/teams/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=teams) - [Advertising](https://stackoverflow.co/advertising/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=advertising) - [Talent](https://stackoverflow.co/advertising/employer-branding/?utm_medium=referral&utm_source=stackoverflow-community&utm_campaign=footer&utm_content=talent) ##### [Company](https://stackoverflow.co/) - [About](https://stackoverflow.co/) - [Press](https://stackoverflow.co/company/press/) - [Work Here](https://stackoverflow.co/company/work-here/) - [Legal](https://stackoverflow.com/legal) - [Privacy Policy](https://stackoverflow.com/legal/privacy-policy) - [Terms of Service](https://stackoverflow.com/legal/terms-of-service/public) - [Contact Us](https://stackoverflow.com/contact) - Cookie Settings - [Cookie Policy](https://policies.stackoverflow.co/stack-overflow/cookie-policy) ##### [Stack Exchange Network](https://stackexchange.com/) - [Technology](https://stackexchange.com/sites#technology) - [Culture & recreation](https://stackexchange.com/sites#culturerecreation) - [Life & arts](https://stackexchange.com/sites#lifearts) - [Science](https://stackexchange.com/sites#science) - [Professional](https://stackexchange.com/sites#professional) - [Business](https://stackexchange.com/sites#business) - [API](https://api.stackexchange.com/) - [Data](https://data.stackexchange.com/) - [Blog](https://stackoverflow.blog/?blb=1) - [Facebook](https://www.facebook.com/officialstackoverflow/) - [Twitter](https://twitter.com/stackoverflow) - [LinkedIn](https://linkedin.com/company/stack-overflow) - [Instagram](https://www.instagram.com/thestackoverflow) Site design / logo © 2025 Stack Exchange Inc; user contributions licensed under [CC BY-SA](https://stackoverflow.com/help/licensing) . rev 2025.10.9.35104
Readable Markdownnull
Shard169 (laksa)
Root Hash714406497480128969
Unparsed URLcom,stackoverflow!/questions/4690600/python-exception-message-capturing s443