Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialnarvesh pradhan
2,958 Pointstry and exception
why try and except function is important in python and what's its function? i am little bit confuse about the video??
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsThe Python try/except
statement allows you to keep your program from crashing by providing a mechanism to handle expected cases. Code in the try
code block is executed, if an error occurs, the except
code will be executed. Well written code will state the specific error that might be a concern. Unexpected exceptions get raise to the user and the program is halted.
user_chosen_file = input("what file should I open? ")
try:
# try code block
file_handle = open(user_chosen_file, 'r')
except FileNotFoundError:
# exception code block
# inform user file not found
print("file {} not found".format(user_chosen_file)
Without using the try/except
statement the program would crash if the file was not found.
A try/except
statement is best used when a program is handling conditions outside of it's control such as dealing with user input or calling functions and objects in other programming modules (OS, databases). Basically, it's useful when you can't guarantee what a code block might do and want to provide a backup plan to keep the program running.