Analyzing exceptions

In this section, we are going to understand analyzing exceptions. Every exception that occurs must be handled. Your log files should also contain few exceptions. If you are getting similar types of exceptions a number of times, then your program has some issue and you should make the necessary changes as soon as possible.

Consider the following example:

f = open('logfile', 'r')
print(f.read())
f.close()

After running the program, you get the output as follows:

Traceback (most recent call last):
File "sample.py", line 1, in <module>
f = open('logfile', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'logfile'

In this example, we are trying to read a file that is not present in our directory and as a result it shows an error. So, from the error we can analyze what kind of solution we have to provide. To handle such a case, we can use an exception handling technique. So, let's see an example of handling errors using an exception handling technique.

Consider the following example:

try:
f = open('logfile', 'r')
print(f.read())
f.close()
except:
print("file not found. Please check whether the file is present in your directory or not.")

After running the program, you get the output as follows:

file not found. Please check whether the file is present in your directory or not.

In this example, we are trying to read a file that is not present in our directory. But, as we used a file exception technique in this example, we put our code in try: and except: blocks. So, if any error or exception occurs in a try: block, it will skip that error and execute the code in an except: block. In our case, we just put a print statement in an except: block. Therefore, after running the script, when the exception occurs in the try: block, it skips that exception and executes the code in the except: block. So, the print statement in the except block gets executed, as we can see in the previous output.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset