Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (Retired) Things That Count Exceptions

narvesh pradhan
narvesh pradhan
2,958 Points

try 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
MOD
Chris Freeman
Treehouse Moderator 68,029 Points

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