Member-only story
How To Use Try / Except Commands In Python
Python has a ton of built in functionality, and one of my favorite commands within Python is Try / Except. These commands allow us to try a certain block of code, if that code doesn’t work it can print out an error. Here is a little breakdown of this functionality:
try:
#PUT THE CDOE TO TRY HERE
except:
#IF THE CODE FAILS, DO THIS INSTEAD
These commands are extremely important, in my experience whenever i’ve built out an application and a certain portion didn’t work within the code, the whole program wouldn’t open / the program would break. If you strategically place try / except commands in your code, the program has a lower chance of breaking in my experience.
First off, let’s start off by typing out “try:”, then skip to a new line as I showcased above, our code will look like this:
try:
At this point, we want to add the code that we wanted to try in this next line, let’s go ahead and try adding a print statement, let’s print out “Try Worked” as written below:
try:
print("Try Worked")
Awesome, now let’s work on the except command. Just in case our try command didn’t work, it will skip to the except command, start off by typing out “except:” just like below:
except:
Now add a new line below that and add a print statement saying “Try Didn’t Work”, just like below:
except:
print("Try Didn't…