In any programming, including Python, exceptions and error handling often becomes a necessity when you are dealing with a considerable amount of variables. When, I say variables I do not mean variables as a placeholder, but variables as in you are using file system processes (like reading a file), dealing with external input, etc. Sometimes, you just do not know what will be thrown at your code. So you being little genius, you plan ahead and use exceptions and error handling where appropriate. Typically, the goal is to execute the code as intended, but if an exception occurs, we would prefer Python not to spit out its own exceptions. Instead, we would like to inform the user what went wrong using our wording and possibly how they can maneuver around the obstacle.
Exceptions vs Errors
I know I keep babbling about exceptions and errors, but what in the heck are they and how are they different you might ask. Well, exceptions generally deal with small little issues that you would probably like to handle. For example, maybe you do not exactly know the type of the variable, but you would definitely like to do something with it. The differences in doing things with numbers and strings are pretty different. So, you might set up something like this:
Awesome! We totally caught the exception that python gave us. We simply put the code we wanted to execute under the try block. However, if an exception occurred (adding a string to and integer is an exception) we told Python to do everything in the except block.
So, what are errors? Bad news, that’s what they are. You normally do not want to handle errors, unless you are doing some dangerous things. When an error is generated, it typically means Python is blowing up the ship, Obviously, if the ship is blown up, we should jump ship and get out of the program.
Also, you might have noticed that the print() takes two arguments in this example. Well, it can take as many arguments as you want to give it. print() will keep on printing all of your arguments with a space in between them.
Elegant Error Handling
Let’s face it our try/except above, doesn’t do a whole lot for the usability of the program. Basically, if it messes up it just tells our users what is wrong. What is the point in that? We should attempt to handle our exceptions in a manner that helps the program to keep moving on. A better alternative would be something like this:
Ah, much better. In this example, we use our simple except to catch an exception. But, if you run the example, you will see something much more awesome happening. We actually catch the exception, and tell python, “Well, try casting it to an integer before adding”, where Python faithfully obeys. As the end result, Python prints out the number 2 and the user is none the wiser that the program had a small hiccup.