Raising and Handling Exceptions in Python – Python Programming Essentials

- - Tutorials

Brief Introduction

Any unexpected events that occur during the execution of a program is known to be an exception. Like everything, exceptions are also objects in python that is either an instance of Exception class or an instance of underlying class derived from the base class Exception. Exceptions may occur due to logical errors in the program, running out of memory, etc..

Common Exception Types

Class Description
Exception A base class for most error types
AttributeError Raised by syntax obj.foo, if obj has no member named foo
EOFError Raised if “end of file” reached for console or file input
IOError Raised upon failure of I/O operation (e.g., opening file)
IndexError Raised if index to sequence is out of bounds
KeyError Raised if nonexistent key requested for set or dictionary
KeyboardInterrupt Raised if user types ctrl-C while program is executing
NameError Raised if nonexistent identifier used
StopIteration Raised by next(iterator) if no element
TypeError Raised when wrong type of parameter is sent to a function
ValueError Raised when parameter has invalid value (e.g., sqrt(−5))
ZeroDivisionError Raised when any division operator used with 0 as divisor
For an example, following produces a TypeError exception
abs(‘hello world’) #expects numeric parameter but string given
Example of ValueError

Although the type of the passed parameter is correct, the value is illegitimate.

int(‘hello world’)
int(‘3.14’)

Raising an Exception

An exception can be raised from anywhere within the program though the keyword raise followed by an instance of any of the exception classes.

For example, when your program is expecting a positive integer to process but the I/O stream sent a negative integer, you could raise an Exception as such:

raise ValueError(‘Expecting a positive integer, got negative’) #instance of ValueError exception class

Handling an Exception

Now that we have talked on raising an exception, we should program such that the exception is dealt as required, else the execution of the program terminates. It is advisible to catch each exception types separately although python allows a more generic exception handling for any type of exceptions that may occur.

Examples of Common Usage:

try: 
    result = x/y
except ZeroDivisionError:
    #do as per required

Other common exception handling:

try:
    fp = open(‘sample.txt’ )
except IOError as e:
    print( Unable to open the file: , e)

Conclusion

Exceptions are an important principles of programming for any languages. It should be used wisely. On a concluding note, a try-except block can have a finally block as well. An example of use of finally can be to close a connection regardless of the successful or failed transmission of messages. Additionally, a try-except combination can have a single try block with multiple except blocks catching various classes of exception.

Follow me on github https://github.com/bhishan

Hire me for a project https://fiverr.com/bhishan

bhishan

I am Bhishan Bhandari, a CS student and life hacker. I specialize in automation. I sell my services on fiverr. You can hire me for projects here Buy Services Follow me on github for code updates Github You can always communicate your thoughts/wishes/questions to me at bbhishan@gmail.com

Leave a Reply

Your email address will not be published. Required fields are marked *