Make your errors meaningful.
ElseSometimes we might want to do something only if everything goes well.
We can add else to our try/except and this will only execute if we didn’t have any issues.
Here we are trying to open a file named my_file.
txt as read-only, denoted by 'r'.
If successful, we read the file’s contents and store it in contents before printing the contents of the file to the console.
If the file does not exist in the same location as our running program, we will hit a FileNotFoundError.
If that happens, we tell the user about what happened and move on.
If this doesn’t happen, we have an open file on our hands, and we need to ensure we close the file to remove any locks so other programs can use the file later.
This is where else comes in.
If it is successful, the else clause executes, and we close the file.
This is working code, so if you want to make a new file called “my_file.
txt” in your working directory this will work, and the file will close when done.
In Python, files are automatically closed for you by garbage collection or when your program exits; however, it is always better to explicitly close any files that you open.
There is a better way to handle file IO, but we will cover that in a future article.
FinallyNo this isn’t the end of the article, but there is a sibling to else called finally.
The difference between the two is pretty easy to understand.
else is only called when the try statement is successful.
finally is always called no matter what.
They can be used separately or together, depending on your need.
If successful, we will see the following output:file opened!Hello, World!file closeddoneIf the file was not found:File not found!doneAn excellent way to start writing your try/except blocks is to begin by separating everything away from each other.
Figure out what kinds of errors might come from error raising functions.
Photo by Peter Hershey on UnsplashCreating Custom ErrorsSometimes our program is so specialized that we need errors of our own that we can return from functions that provide the specificity to tell our user what went wrong.
We have two choices, either adopt an error that Python already has, or create one of our own.
Let’s look at adopting from Python first.
For this example, we are going to accept a string parameter, but we expect it only to contain spaces.
In the two examples, the first data value is correct, and we see a value of 10 displayed in our console.
In the second example, we have tabs ( ) in place.
The first thing our function does is check if data contains tabs.
If it does it raises a TabError.
The error itself is disconnected from the data string; it doesn’t care about the contents.
It’s just an error that you can use to provide a meaningful stop in your program if things don’t go as planned.
If you try printing the string value of TabError you will get back None.
If you wanted to include an error message more tailored to the situation at hand, you could change the function to read as such:This would allow you to use TabError as error like we did above and display that as an error message instead.
This is preferred, this way, you only need to worry about returning your error message instead of creating one every time you call this function.
Of course, if you need logic in your error message, you can adjust one or both messages to meet your needs.
If you need something even more special than this, you can always create your own error.
Here we create an exception named BadData it subclasses from Exception which is what we should be using for all of our errors.
I added in a docstring which helps us understand what it should be used for when we see the automatic documentation for BadData.
Then we pass because we don’t need to do anything more.
We run through our program, and if we have a file containing levels, then we continue processing the contents.
If not, then we raise our exception and catch it below.
Because our exception is a class, we can use it anywhere it is needed.
It’s straightforward and provides a lot of functionality for you to handle errors that the system may not understand.
Always create custom exceptions if you cannot find one suitable for your needs and there is no better way to refactor your code to handle that error without using try/except.
Re-RaiseSometimes you might call an exception deep in a stack of functions and need it to bubble back up to the top.
In scenarios like this, you can use raise to continue raising the same exception back up through the stack until you are ready to handle it.
Here I’m just using a NotImplementedError because well, we haven’t completed the function yet.
some_other_func calls make_error using a try/except block.
If we receive a NotImplementedError we raise it again so we can handle it in our main body where we print “Not implemented.
” While this is a simple example, it gives you a good idea of how it works.
SummaryToday we learned how errors occur and how we can handle them if they do.
We learned several techniques for keeping your program running under less than ideal conditions as well as differences between proper error handling and lousy error handling.
If you’ve downloaded PyCharm, you can type raise, then ctrl + space to see some of the exceptions that you can use.
If you have been brave enough to get involved with modules from other places, you can even see the different exceptions they have created for you concerning their projects.
Suggested ReadingChapter 8 of the Python Tutorial8.
Errors and Exceptions — Python 3.
3 documentationEven if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute…docs.
orgWhat’s NextCode Structure and Readability is what’s next.
It’s about time that we learn how to structure our code under PEP 8 standards properly.
We might also cover docstring conventions defined in PEP 257.
If you are going to write good Python programs, you need to understand those PEP standards and abide by them at a minimum.
Until then, see if you can handle pesky errors that may have popped up in some of your projects.
Make it so that you can throw whatever data you want at your application and it intelligently responds to your misgivings.
.. More details