
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to capture and print Python exception message?
Python exception messages can be captured and printed in different ways as shown in two code examples below. In the first one, we use the message attribute of the exception object.
Example
try: a = 7/0 print float(a) except BaseException as e: print e.message
Output
integer division or modulo by zero
In case of given code, we import the sys module and use the sys.exc_value attribute to capture and print the exception message.
Example
import sys def catchEverything(): try: a = 'sequel' b = 0.8 print a + b except Exception as e: print sys.exc_value catchEverything()
Output
cannot concatenate 'str' and 'float' objects
- Related Articles
- How to capture an exception raised by a Python Regular expression?
- How to implement a custom Python Exception with custom message?
- How to capture null reference exception in C#?
- What are the different ways to print an exception message in java?
- How to print the Python Exception/Error Hierarchy?
- How to capture divide by zero exception in Java?
- How to capture file not found exception in Java?
- How to capture divide by zero exception in C#?
- How to capture file not found exception in C#?
- How to capture out of memory exception in C#?
- How to capture index out of range exception in C#?
- How to capture the text from Alert Message in Selenium Webdriver?
- How to print exception messages in android?
- How to capture out of array index out of bounds exception in Java?
- How to capture SIGINT in Python?

Advertisements