
- 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 get Python exception text?
If a python code throws an exception, we can catch it and print the type, the error message, traceback and get information like file name and line number in python script where the exception occurred.
We can find the type, value, traceback parameters of the error
Type gives the type of exception that has occurred; value contains error message; traceback contains stack snapshot and many other information details about the error message.
The sys.exc_info() function returns a tuple of these three attributes, and the raise statement has a three-argument form accepting these three parts.
Getting exception type, file number and line number in sample code
import sys, os try: raise NotImplementedError("No error") except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno
- Related Articles
- How to get text with selenium web driver in python?
- How to handle an exception in Python?
- How to catch KeyError Exception in Python?
- How to raise an exception in Python?
- How to catch IOError Exception in Python?
- How to catch ArithmeticError Exception in Python?
- How to catch OverflowError Exception in Python?
- How to catch IndexError Exception in Python?
- How to catch NameError Exception in Python?
- How to catch EOFError Exception in Python?
- How to catch SyntaxError Exception in Python?
- How to catch IndentationError Exception in python?
- How to catch TypeError Exception in Python?
- How to catch EnvironmentError Exception in Python?
- How to catch LookupError Exception in Python?

Advertisements