Learn Python With Dhawal - 17 - Handling Errors and using Exceptions

Previously, we learnt about File handling. Did you try something else apart from the course instruction program? If you have, there'll be a fair chance that you must have encountered some sort of errors. Debugging for errors is one thing that we always have to do as a precaution. But what if there are case scenarios where there's some issue with a portion of code, but that code might be important or you can still run the program successfully after failure of one particular method.

Error Handling

Imagine there's a calculator program and you want to take input amounts from the users, but the user didn't give any input or say there was a failure in catching input or maybe wrong input was given. What would you do? In the previous coding examples that we have done, they program will simply throw an error and would stop it's execution.

In some scenarios we can handle complete halt of execution but imagine a code written to run atomic cooling plants or power plants or even hospital ventilation systems or say power grid? Running into some stupid error might result in complete halt of the execution and might result in huge losses of both life and finance.

To handle errors programmers often build some mechanisms but it's not possible that we can always have a mechanism in place. So to counteract with such situations we have something called Error handling mechanisms. We use exceptions to just get past around some situations still making the code finish it's execution and turn get into a stable state.

For example : Imagine you wrote a code for running a banking application. There was a power loss and before that you had sent the message to send the money from account A to B, but in midst, before the message could reach B, there was a power failure. Now the A would assume that he has sent the money but B will still be waiting for money. This can result in chaos if that happened at a larger level. (I know there will be database management here, but just giving an example, so don't overthink). To counteract such cases, we create a kind of a failsafe mechanism. There we create an exception.

What is an Exception?

Just like the name suggests, we give error situation an exception and allow the code to run further. It's like giving it an excuse to continue without total halt of the system. Continuing from the same above example of a banking scenario.

Now, after the power has been restored, we had built in an exception inside the program. If something like that had happened and we received no acknowledgement from B about receiving the money, we would reinstate the balance amount in A's account and then sent the money again or just inform the details about the failure to the server manager and user stating about the failure of the transaction.

Further it would depend on the build of the system to either resend the request or cancel the transaction altogether.

Using Exceptions in Real time Code.

Imagine in the previous file handling program. You wrote a code to open a file and read it. Now, if the file didn't exist, you'd get an error and program execution would be halted. Now, we can write a code that if the file previously mentioned don't exist, we can give user an option to create a new file and then read the it using the program. We do it with the help of the 'try....catch/except' blocks. Where 'try' is used to try a particular code and 'catch/except' is used to mention incase the code inside the 'try' block failed execution. There's also an option of a default code block which can be called either 'default/finally' this block of code is executed in all case scenarios irrespective of the execution of try and catch blocks.

Syntax : 

try :
except nameOfError:
finally :

Here, inside the try block you'd write all the code that you have doubt about having a failure. Now with the except block you can counter all the errors at once or counter exceptions depending on their type. If you don't mention the name of the error you want that particular block of except code to handle then it'll be used in all case scenarios of failure. It might not be smart as at times knowing what's the issue can be a lot more helpful and can be remedied. For example, if user didn't enter their name then you can use default name temporarily and then alert user about it or if you are using a calculator program then you can use 0 or 1 depending on what the previous operation was and alert the user about data input failure.

You can also add an 'else' block here to be executed in a scenario where no errors have occurred. Not sure where this would be useful but it's a handy thing to know. Now before we begin actual coding, I want you to try the name of the error where file is not been found. Open a new python file, write a code to just open a desired file but which doesn't exist. See the output and copy the error name and save it somewhere just incase for our code.

Input :

import os
try :
    f = open("C:/Users/joshidhawal/Documents/Git/learn-python-with-dhawal/testfile.txt","r")

except  FileNotFoundError:
    print ("The desired file is not found, we will create one for you instead.")
    f = open("C:/Users/joshidhawal/Documents/Git/learn-python-with-dhawal/testfile.txt","a+")
    print("A new file is created")
    f.write("Hello World!")
    print("Message is written in it.")
    print("The cursor is moved to beginning of file")
    print("The message is read")
    print("File is closed")
    print("the file is been deleted")
Output :

  1. The desired file is not found, we will create one for you instead.
  2. A new file is created
  3. Message is written in it.
  4. The cursor is moved to beginning of file
  5. Hello World!
  6. The message is read
  7. File is closed
  8. the file is been deleted
Explanation :

Now, I have tweaked this code a little bit. In previous chapter we were using directly appending mode to read-write a file. But if we are just reading a file and not bothered about writing it. This is the error handling mechanism we can use. Here, we have previously found out the 'FileNotFoundError' is the one we want to handle and leaving the other errors aside for later.

We use the try block and put the read file statement inside it. But when that reading a file gives an error which we have previously expected, we already had corrected exception kept in place for it. So the instead of programming blindly for every possible exception, we targeted a thing that we could remedy.

We just created a file, wrote into it and rest is the standard procedure as we know from the previous program.

Note : We can use console log statements instead of printing the states but this is for the further advanced chapters. For now, we have used print statements as a part of logging mechanism to know what's happening in the program.

Input :

try :
    a=int(input("Divide 10 by : "))
except ZeroDivisionError :
    print("You can't divide by zero, enter a valid number again")
    a=int(input("Divide 10 by : "))
except Exception as e:
    print("Some error occured\nError Description : "+str(e))
    print("Sorry, run the program again")

Output :

  1. Divide 10 by : 
  2. Some error occured
  3. Error Description : invalid literal for int() with base 10: ''
  4. Sorry, run the program again
Explanation : 

Here we have added a parameter to catch other errors than the ones we had previously planned for. Here when someone forgets to enter and just presses enter, it'll catch the particular exception and then display the error without stopping the execution of your code. We just create an object of the main 'Exception' class as 'e' and then use it to catch the errors. We later just print the description of error and finish execution of code without any errors technically.

Input :

Here we just added an if statement inside out try block after the input statement to give an error if someone entered a negative number in the previous code.

try :
    a=int(input("Divide 10 by : "))
    if (a<0):
        raise Exception("Enter anything else please!")

Output :

  1. Divide 10 by : -10
  2. Some error occured
  3. Error Description : Enter anything else please!
  4. Sorry, run the program again

Explanation :

Now, there will be times when you want to raise/throw exceptions of your own in certain cases, for example say while sending amount in a bank transaction, it shouldn't be negative. You can't send someone -100₹ or -100$ per say. That would be a joke and a disaster if someone finds that bug out. So in such case scenarios we write custom exceptions. To raise/throw a custom exception, we have a keyword 'raise' here in python. We will write a conditional statement and depending on that we will decide whether to throw/raise an exception or not. We can throw/raise any exception we want, here I have raised a custom exception but you can find out exceptions of your choice and deploy them as your wish and will.

With this I hope you had grasped all the basics about exceptions and how to handle them if you come across them during your coding  adventures. Feel free to try out some custom exceptions and experiment around a bit here and there.


Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Are you getting regular fresh content updates? If not click on the button below.


Post a Comment

Do comment and share your thoughts.