As I mentioned on my first post, before starting this blog I did take CS 101 Intro to Computing Science at Udacity (Although I have forgotten 99% of it), which was pretty much my first ever encounter with code. The exercises and class used python as a language to learn, and so of course Python will be the language I will be focusing on more at the beginning and will try to become good at it.
Today for a complete random reason I decided to look into some simple code and saw that TRY and EXCEPT was being used. So I watched some videos about it on youtube like the ones below, and it all became clear:
- Python Basics: Try and Except
- Python Tutorial: Using Try/Except Blocks for Error Handling
- Python 3 Programming Tutorial – Try and Except error Handling
- Let’s Learn Python – Basics #5 of 8 – Exception Handling
TIP: Whenever you don’t know something, try to find at least 3/4 different videos explaining the same thing. You will learn different things and approaches from each video.
So. what is the role of Try/Except?
Well, programs sometimes crash. Python is a program that will not “compile” before running, which means that it will run even if there is a bug. At the same time, whenever it reaches a bug, then it will stop, and it will show you an Error and some information so that you know where things went wrong.
Now, what if we don’t want the program to stop if there is an error, and instead we want the program to do more things whenever there is an error, even continuing with the next lined? That is exactly the purpose of Exception Handling, which is done through TRY and Except.
Try and Except allows you to tell the computer what to do, whenever there is an error, or even more specifically, what to do if ever there is a specific kind of error. I imagine that other programming languages will also have similar commands to do same thing.
Now, in terms of what to use, the recommended option is to use except Exception as e: and then print (e) as the image on the header. This will basically catch any kind of error in the code analyzed and will display the error message in a nice way so that you can act on it.
Final conclusions
- It is used in parts of the code that are more prone to error
- It is used to avoid the program to stop if there is indeed an error
- It is used to tell the program what to do whenever an error happens
Things not yet fully understood
Whenever an error is found, then the EXCEPT part of the try/except clause is called and runs. However, if there was still more code inside that try/error block, after the first error happened, that code will not be read and you will then lose info on that section.
How do you then make sure that this doesn’t become a problem? Is there any way to tell the computer that after an error is found, then it should keep going from the next line after the line in which it found the error, so that further stuff can also be found?
Best.