Python Practice › Exception Handling Programs › Program 17
Print exception details
Write a Python program that prints the type, message and line of a caught exception.
Output
type: IndexError message: list index out of range line: 3
Approach
type(e).__name__,str(e)and the traceback object.
Solution
try: numbers = [1, 2, 3] numbers[5]except IndexError as e: tb = e.__traceback__ print("type:", type(e).__name__) print("message:", e) print("line:", tb.tb_lineno)Output
type: IndexError message: list index out of range line: 3
Line by line
Line 5
__traceback__ holds where the error happened; tb_lineno is the line number.
Learn the concept
New to this topic? Read the lesson, then come back.