Print exception details

EasyException Handling Programs · 17 of 20

Write a Python program that prints the type, message and line of a caught exception.

Advertisement
Output
type: IndexError
message: list index out of range
line: 3

Approach

  1. type(e).__name__, str(e) and the traceback object.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment