What are exception?

Exception are events that causes the program flow to modify. In python, exception are triggered automatically when python encounters error. There are four forms of statements to handle exceptions:
  • try/except
  • try/finally
  • raise
  • assert
  • with/as
 These are called exception statements. These exception statement allows us to cause jump from one place in a program because something went wrong there to another part of the program that handles the error, called the exception handler. This is thus like interrupt concept in c/c++ programming language.

What are example of circumstances where exception are used?

Exceptions are used in and for the following situation
  • To handle error
When there is error in the program, python will detect it and will by default stop the program and spit error. But one can catch and respond to those errors. To catch the error one can use the try statement that causes the program to execute try handler. After the try handler, the control goes back to the point where the error was encountered.
  • Event notification
One can use exception to monitor certain event in the program. When the event occurs, exception will cause message to be displayed.
  • Special case handling
 There might be cases which are not usually and ordinarily observed. Exception can be used to handle such special cases.
 Simple example of try/except exception

Consider a list which has 4 elements:

L = ['john', 'jerry', 'micheal', 'ron']

 If we try to get the 5th element, L[4] we will get IndexError informing that there is no 5th element:

L = ['john', 'jerry', 'micheal', 'ron']

print(L[4])
 
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:...undle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "D:\python\....\exceptions.py", line 4, in <module>
    print(L[4])
IndexError: list index out of range

A simple example to handle this error is to use the try/except exception statement. In this case, we catch the IndexError if there is any and display a message using the except statement as follows.

L = ['john', 'jerry', 'micheal', 'ron']

try:
    print(L[8])
except IndexError:
    print('no index')

 If we call/run this in command console:

>>> import exceptions
no index

The message no index will be displayed by the exception handler. Thus we avoided the default IndexError message.

Next see Examples of Exception in Python.

0 comments:

Post a Comment

 
Top