An integral part of using Python involves the art of handling exceptions. There are primarily two types of exceptions; Built-in exceptions and User-Defined Exceptions. In such cases, the error handling resolution is to save the state of execution in the moment of error which interrupts the normal program flow to execute a special function or a code which is called Exception Handler.
There are many types of errors like ‘division by zero’, ‘file open error’, etc. where an error handler needs to fix the issue. This allows the program to continue based on prior data saved.
Source: Eyehunts Tutorial
Just like Java, exceptions handling in Python is no different. It is a code embedded in a try block to run exceptions. Compare that to Java where catch clauses are used to catch the Exceptions. The same sort of Catch clause is used in Python that begins with except. Also, custom-made exception is possible in Python by using the raise statement where it forces a specified exception to take place.
Errors are always expected while writing a program in Python which requires a backup mechanism. Such a mechanism is set to handle any encountered errors and not doing so may crash the program completely.
The reason to equip python program with the exception mechanism is to set and define a backup plan just in case any possible error situation erupts while executing it.
Try statement is used for handling the exception in Python. A Try clause will consist of a raised exception associated with a particular, critical operation. For handling the exception the code is written within the Except Clause. The choice of performing a type of operation depends on the programmer once catching the exception is done.
The below-defined program loops until the user enters an integer value having a valid reciprocal. A part of code that triggers an exception is contained inside the Try block.
In case of absence of any exceptions then the normal flow of execution continues skipping the except block. And in case of exceptions raising the except block is caught.
Checkout the example:
The Output will be:
Naming the exception is possible by using the ex_info() function that is present inside the sys module. It asks the user to make another attempt for naming it. Any unexpected values like 'a' or '1.3' will trigger the ValueError. Also, the return value of '0' leads to ZeroDivisionError.
There are instances where the suspicious code may raise exceptions which are placed inside such try statement block. Again, there is a code that is dedicated to handling such raised exceptions and the same is placed within the Except block.
Below is an example of above-explained try and except statement when used in Python.
try:
** Operational/Suspicious Code
except for SomeException:
** Code to handle the exception
To define the Except Clause isn’t always a viable option regardless of which programming language is used. As equipping the execution with the try-except clause is capable of handling all the possible types of exceptions. It will keep users ignorant about whether the exception was even raised in the first place.
It is also a good idea to use the except statement without the exceptions field, for example some of the statements are defined below:
try:
You do your operations here;
......................
except:
If there is an exception, then execute this block.
......................
else:
If there is no exception then execute this block.
OR, follow the below-defined syntax:
try:
#do your operations
except:
#If there is an exception raised, execute these statements
else:
#If there is no exception, execute these statements
Here is an example if the intent is to catch an exception within the file. This is useful when the intention is to read the file but it does not exist.
try:
fp = open('example.txt', r)
except:
print ('File is not found')
fp.close
This example deals with opening the 'example.txt'. In such cases, when the called upon file is not found or does not exist then the code executes the except block giving the error read like 'File is not found'.
It is possible to deal with multiple exceptions in a single block using the try statement. It allows doing so by enabling programmers to specify the different exception handlers. Also, it is recommended to define a particular exception within the code as a part of good programming practice.
The better way out in such cases is to define the multiple exceptions using the same, above-mentioned except clause. And it all boils down to the process of execution wherein if the interpreter gets hold of a matching exception, then the code written under the except code will be executed.
One way to do is by defining a tuple that can deal with the predefined multiple exceptions within the except clause.
The below example shows the way to define such exceptions:
try:
# do something
except (Exception1, Exception2, ..., ExceptionN):
# handle multiple exceptions
pass
except:
# handle all other exceptions
You can also use the same except statement to handle multiple exceptions as follows −
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is an exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
Apart from implementing the try and except blocks within one, it is also a good idea to put together try and finally blocks.
Here, the final block will carry all the necessary statements required to be executed regardless of the exception being raised in the try block.
One benefit of using this method is that it helps in releasing external resources and clearing up the cache memories beefing up the program.
Here is the pseudo-code for try..finally clause.
try:
# perform operations
finally:
#These statements must be executed
The example given below executes an event that shuts the file once all the operations are completed.
try:
fp = open("example.txt",'r')
#file operations
finally:
fp.close()
Again, using the try statement in Python, it is wise to consider that it also comes with an optional clause – finally. Under any given circumstances, this code is executed which is usually put to use for releasing the additional external resource.
It is not new for the developers to be connected to a remote data centre using a network. Also, there are chances of developers working with a file loaded with Graphic User Interface.
Such situations will push the developers to clean up the used resources. Even if the resources used, yield successful results, such post-execution steps are always considered as a good practice. Actions like shutting down the GUI, closing a file or even disconnecting from a connected network written down in the finally block assures the execution of the code.
The finally block is something that defines what must be executed regardless of raised exceptions. Below is the syntax used for such purpose:
The file operations example below illustrates this very well:
Or In simpler terms:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Constructing such a block is a better way to ensure the file is closed even if the exception has taken place. Make a note that it is not possible to use the else clause along with the above-defined finally clause.
Python users can create exceptions and it is done by deriving classes out of the built-in exceptions that come as standard exceptions.
There are instances where displaying any specific information to users is crucial, especially upon catching the exception. In such cases, it is best to create a class that is subclassed from the RuntimeError.
For that matter, the try block will raise a user-defined exception. The same is caught in the except block. Creating an instance of the class Networkerror will need the user to use variable e.
Below is the syntax:
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
Once the class is defined, raising the exception is possible by following the below-mentioned syntax.
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
Note that an exception is an error that occurs while executing the program indicating such events (error) occur though less frequently. As mentioned in the examples above, the most common exceptions are ‘divisible by 0’, ‘attempt to access non-existent file’ and ‘adding two non-compatible types’. Ensure putting up a try statement with a code where you are not sure whether or not the exception will occur. Specify an else block alongside try-except statement which will trigger when there is no exception raised in a try block.
Shahid Mansuri Co-founder Peerbits, one of the leading software development company, USA, founded in 2011 which provides Python development services. Under his leadership, Peerbits used Python on a project to embed reports & researches on a platform that helped every user to access the dashboard that was freely available and also to access the dashboard that was exclusively available. His visionary leadership and flamboyant management style have yield fruitful results for the company. He believes in sharing his strong knowledge base with a learned concentration on entrepreneurship and business.
Fake Python libraries removed from PyPi when caught stealing SSH and GPG keys, reports ZDNet