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 trialmohit jain
1,060 Pointshow is try and except blocks different than using if else function in your code?
I was just wondering if we can use if else statements instead of try and except and what value des try/except add over if/else statement.
2 Answers
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi Mohit
The name itself explains it, try and except is more for exception handling where as if and else is more for executing code based on a condition. When you put code between a try block python will try and execute the code or throw an error if it cannot, thats where the except comes in. The except block helps you catch the exception and display an appropriate error to the user. If block will only execute if a condition is met.
see an example
try:
my_input = input("Enter a number")
except ValueError:
print("This is not a number")
# this example helps us catch an exception if the user does not enter a number. Try and except is also great when you are trying to debug code and not sure what the error is.
# assume we are trying to send an email
try:
sendemail(example@example.com,example@example2.com)
except Exception as e:
print(str(e))
# i can catch any error that occurs which helps me debug the code assuming the sendemail function doesnt send an email
# the if statement is more a conditional statement and is not meant for exception handling.
mohit jain
1,060 PointsThanks Andreas. It makes sense now :)