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 trial

Python

Hello, Why use the try/ except block code to handle error and exceptions? Why not if conditions and loops?

Why use the try/ except block code to handle error and exceptions? Why not if conditions and loops?

1 Answer

Try Catches allow you to "catch" actual errors, like fatal errors, etc.

For instance, let's say you do an API call, but the server isn't 'responding. You won't get back a condition for If/else statements. You will get an error about it timing out.

A Try / Catch will handle this.

This is actually something part of a Try, Catch, Finally.

So this allows you to attempt to do a process that actually has a possibility of failing (error). If Else doesn't believe an error will likely occur in its running, but rather is trying to figure out how to handle non-error responses.

If else works well for "If the day is Saturday, then sleep in. Else, wake up on time."

Try Catch works well for "Call a server and ask for a web page. Oh no, the server is down / don't have access, and an error returns." Normally big errors will crash your app. With Try, Catch, you could show an error to the user without crashing the program.