Thursday, August 20, 2020

A Guide to Python Exception Handling



Hello dear readers! welcome back to another section of my tutorial on Python. In this tutorial, we will be discussing about the Exception Handling in Python.

Python program provides two very important features to handle any unexpected error in your programs and as well to add debugging capabilities in them -

  • Exception Handling - This is going to be discussed in this tutorial. Here is a list of Standard Exceptions which are available in Python.

What is Exception?

An exception is an event, which occurs during program execution that alters the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it instantly raises an exception. An exception is a Python object that represents an error.

Whenever a Python script raises an exception, it must either handle the exception immediately else, it terminates and quits.

Handling an Exception

If you have a suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, you should include an except: statement, then followed by a block of code which takes care of the problem as nice as possible.


Syntax

Below is the syntax of try...except.. else blocks -

try:
   You do your operations here;
   ......................
except ExceptionI:
   If there is ExceptionI, then execute this block.
except ExceptionII:
   If there is ExceptionII, then execute this block.
   ......................
else:
   If there is no exception then execute this block.

Here are few important points to be noted about the above syntax -

  • A single try statement in Python can have different except statements. This is useful when the try block consists of statements that may throw different types of exception.
  • A generic except clause can also be provided, that takes care of any exception.
  • After the except clause(s), you can include an else-clause. The code in the else-block executes if the code inside the try: block does not raise an exception.
  • The else-block is a good place for code that doesn't need the protection of the try: block.

Example 1

The below example opens a file, then writes content to the file, and comes out without any problem at all -

#!/usr/bin/python

try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"
   fh.close()

Output

When the above code is executed, it will produce the following result -

Written content in the file successfully


Example 2

The following example below tries to open a file where you do not have a write permission, so it then raises an exception -

#!/usr/bin/python

try:
   fh = open("testfile", "r")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"

Output

When the above code is executed, it will produce the following result -

Error: can't find file or read data

The except Clause with No Exceptions

The except statement can be used with no exceptions which can be defined as follows -

try:
   You do your operations here;
   ......................
except:
   If there is any exception, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

This kind of try-except statement catches all the exceptions that occur on the program. Using this kind of try except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer spot the root cause of the problem which may occur.


The except Clause with Multiple Exceptions

You can also make use of except statement in handling different exceptions as follows -

try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

The try-finally Clause

You can make use of a finally: block along with a try: block. It is a place to put any code that must execute, whether try-block raised an exception or not. The syntax for the try-finally statement is as follows -

try:
   You do your operations here;
   ......................
   Due to any exception, this may be skipped.
finally:
   This would always be executed.
   ......................

You can not use else clause as well along with a finally clause.

Example

#!/usr/bin/python

try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
finally:
   print "Error: can\'t find file or read data"

Output

If you do not have permission to open the file in writing mode, then this will produce the following result -

Error: can't find file or read data


The same example can be written more neatly as follows -

#!/usr/bin/python

try:
   fh = open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print "Going to close the file"
      fh.close()
except IOError:
   print "Error: can\'t find file or read data"

Whenever an exception is thrown in the try block, the execution instantly passes to the finally block. After all of the statements in the finally block are executed, the exception is raised again and is then taken care of in the except statements if it is available in the next higher layer of the try-except statement.


Arguments of an Exception

An exception is allowed to have an argument, which is a value that gives additional information about the problem. The contents of the argument varies by exception. A Python exception's argument can be captured simply by supplying a variable in the except clause as it is shown below -

try:
   You do your operations here;
   ......................
except ExceptionType, Argument:
   You can print value of Argument here...

If you write a code to handle a single exception, you can have a variable to follow the name of the exception in the except statement. If in a case where you are trapping various exceptions, you can have a variable follow the tuple of the exception.

The variable receives the value of the exception mostly containing the cause of the exception. The variable can of course receive a single value or multiple values in the form of a tuple in the program. This tuple normally holds the error string, error number, and the error location.

Example

Following is an example for a single exception -

#!/usr/bin/python

# Define a function here.
def temp_convert(var):
   try:
      return int(var)
   except ValueError, Argument:
      print "The argument does not contain numbers\n", Argument

# Call above function here.
temp_convert("xyz");

Output

When the above code is executed, it will produce the following result -

The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'


Raising an Exception
You can raise exceptions in many ways by using the raise statement.

Syntax
The syntax for the raise statement is as follows -

raise [Exception [, args [, traceback]]]

From the above syntax, Exception is the type of exception (example, NameError) and the argument is a value for the exception argument. The argument here is optional; if it is not supplied, then the exception argument is None.

The final argument, traceback is also optional (and rarely used in practice), and if it is present, is the traceback object used for the exception.

Example
An example can be a string, class or an object. Most exceptions that core Python raises are classes, with an argument which is an instance of the class. Defining new exception is quite simple and can be done as follows -

def functionName( level ):
   if level < 1:
      raise "Invalid level!", level
      # The code below to this would not be executed
      # if we raise the exception

Note - To catch an exception, an "except" clause must refer to the same exception which is thrown either class object or string. For example in order to capture the above exception, we must write the except clause as it is shown below -

try:
   Business Logic here...
except "Invalid level!":
   Exception handling here...
else:
   Rest of the code here...

RECOMMENDED POST: Python Operators

User Defined Exceptions
Python allows you to create your own exceptions through deriving classes from the standard built-in exceptions.

Here is an example that is related to RuntimeError. In the example, a class is created which is then subclassed from RuntimeError. It is useful when you need to show more information that is specific whenever an exception is caught

In the try block, the user-defined exception is raised and caught in the except block. The variable e is used in creating an instance of the class Networkerror.

class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg

Once you define above class, you can raise the exception as follows -

try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print e.args


Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial post, am going to be dropping you guys with the List of the Standard Exceptions in Python.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.