Printing Exception message
Lesson 6 of 16 in Coddy's Exception Handling in Python course.
f = open("data.txt",encoding='utf-8')
my_data = f.read()
print(my_data)If data.txt doesn't exist, FileNotFoundError will be raised and below message gets printed on console.
Traceback (most recent call last):
File "C:/Users/Lenovo/Desktop/example.py", line 1, in <module>
f = open("data.txt",encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'Above message includes Traceback details --> Exception Name --> Exception Message.
We can print above details in except block so user will get an idea what happened.
syntax:
except ExceptionName as object_Name:
print(object_Name)
try:
f = open("data.txt",encoding='utf-8')
my_data = f.read()
print(my_data)
except FileNotFoundError as obj:
print(obj)If data.txt doesn't exist, control goes to except block and Exception message will be stored in 'obj' object and it will be printed.
Challenge
EasyYou will have list as input. Write a program to sum all elements in a list. If it encounters an exception during summation, it will raise an Exception. Otherwise, it will print summation. The Exception type is TypeError and text will be standard message text. (use for loop only and not sum())
Try it yourself
def summation(my_list):
#your code hereAll lessons in Exception Handling in Python
4Customization/best practices
Customize Tracebacks2Exception Handling
try-exceptelseFinallyPrinting Exception messagePrinting Exception NameHandling Multiple Exceptionssys module for information