Python Exception Handling Beginner Tutorial
As the literal meaning of Exception, in programming, exception handling is the technique for handling the exceptions which occur during program execution.
For example, Python exception handling is the technique for handling exceptions in the python way.
Python Exception Handling
In this python exception handling beginner tutorial, you will learn how to handle exceptions in your python programs. We have explained it with working code blocks.
This is what you would be doing in exception handling.
- Find all the possibilities of exceptions.
- Identify the python exception category.
- Handle the exceptions.
The try except block
In python, an exception is handled in the try except
block. It has the following format.
try: except:
The operation you want to perform goes into the try
block and other error handling operations go into the except
block.
Let’s learn the python exception handling using a python program which creates a directory. Let’s take the following code as an example.
import os import sys directory = "demodir" def createDir(dir): try: os.mkdir(dir) except: print("An Error Occured", sys.exc_info() ) createDir(directory)
The above code has a method named createDir
with an dir
argument. If you execute the above code, a directory named demodir
will be created in the current working directory.
If you execute the same program again, you will get the following output with error details.
('An Error Occured', (<type 'exceptions.OSError'>, OSError(17, 'File exists'), ))
So what happened
When you executed the code for the first time, the code in the try block got executed and it created a directory.
For the second time, it tried to execute the code in try block but a directory named demodir
already exists.
That exception was caught by the except block and it printed the error message specified in that block. Also, it printed the type of exception which occurred OSError
using the sys.exc_info()[0]
function.
Now we know that the type of exception that occurred was an OSError
You can modify the except block as follows to have a meaningful output.
except OSError: print("Folder already Exist. Please delete it or try with a different name")
Now, if you execute the program, you will see the error message specified in the except block.
Likewise, you can have many except blocks to handle different error categories. When you write programs, it is not sure that only one type of error would occur. So you need to find all the possible exception errors and declare it in the except block as shown below.
try: # main operation except OSError: # handles OSError exception except (ArithmeticError, EnvironmentError): # handles differnt exceptions except: # handles exceptions which are not mentioned above
Defining Custom Exceptions
In some situations, you might want to register custom exceptions. Let’s say, you want to add a condition like, there should not be any special characters in the directory name. In this case, you can create and condition and raise
an exception if the user tries to create a directory with special characters.
Take a look at the following example and try executing it.
import os import sys directory = "demodir_" symbols = "~!@#$%^*()_-+={}[]:>;',</?*-+" def createDir(dir): try: if any(char in symbols for char in directory): raise ValueError("The directory name contains special characters. Please use only alphabets") os.mkdir(dir) except ValueError as ve: print(ve) except OSError: print("Folder already Exist. Plese delte it or try with a differnt name") createDir(directory)
In the above example, we have renamed the directory with a special character. Also, the symbols
variable contains a list of special characters. And we are checking for special characters in the directory name in the try
block. Since our directory has a special character mentioned in the symbols variable, it will raise an exception and print the exception using the except ValueError as ve
block. Basically ve
contains the error message raised in the try block.
The finally block
In certain cases, you might want to run a certain code block even if the program has an exception. In this case, you can use the finally
block. It is used in conjunction with the try block.
Let’s take an example where you want to log every attempt for directory creation. In this case, you need a log the directory creation attempt even it raises an exception. Let’s take a look at the following try block.
finally: with open("directory.log", "a") as myfile: myfile.write("directory creation attempted at %s" % str(datetime.datetime.now()))
Add import datetime
at the top and add the above block after all exceptions. Also, create a directory.log file in the current working directory.
Now if you execute your program, you will see the logs with a timestamp appended to the directory.log
file.
Conclusion
I hope you understood the python exception handling concepts and scenarios. This is one of the best for Python’s exceptional handling. If you liked this article, please share it using the social media buttons.
Tnx for this guide, explained it very bright and clear with practical benfits!
looking for more guides like these:
Debugging python scripts
Working with Linux system configuration.
Monitoring alerts using python