Python exception handling

bongobinary logo - python exception handling

What are Exceptions:

Exceptions are events which can occur during the execution of a program due to incorrect code or input. Its good that they are managed properly to avoid termination of the running program.

 

How exceptions occur:

When error occur in a program, exception object is created and handled to the run-time system. The exception object contains information about the error, this information include the type of the error, when it occurred and under what state program was.

 

What is Exception handling

Exception handling is the process of making sure that thrown exceptions from the running program do not affect the whole program in execution.

Python exception example:

history = 12
mathematics = 80
total_subjects = 0

average_score = (history + mathematics )/total_subjects #Zero division error will be thrown.

ZeroDivisionError: division by zero

 

ZeroDivisionError is just one type of exception which can be thrown while program is executing due to incorrect input. There are many other exceptions which can be thrown during the program excecution such as : - Import Error When the import fails, NameError when unknown variable is used. Value error when value of correct type but of un appropriate value. There are many others exception in python which this article can not cover, infact during your whole career in python programming you will not be able to know them all. Many libraries are created and many more Exceptions classes are introduced.

 

How to handle Exception in python? ( how to prevent termination of program due to exceptions)

As with many other languages python handle exceptions by wrapping the code which is likely to throw an exception in a try except block.

python try except example:

>>> try:
...     history = 20
...     mathematics = 80
...     total_subjects = 0
...     average_score = (history + mathematics) / total_subjects
... except:
...     print("Some error occured")
... 
division by zero
>>> 

 

as shown on the example the code which is likely to throw an exception is placed between the the try and except block. The information about the exception can be displayed on the except block. As it was shown while printing information on the example above.

 

How to get Exception object information.

Exception object information.

You can easily get information about the exception which occurred in the program as shown on the code example. Notice that on the Except block we introduced Exception type and we refered to it as e. ( This is for all kind of exception as its the super class of all Exceptions in python)

>>> try:
...     history = 20
...     mathematics = 80
...     total_subjects = 0
...     average_score = (history + mathematics) / total_subjects
... except Exception as e:
...     print(str(e))
... 
division by zero
>>> 

 

Handling specific exceptions:

The examples provided above only show way of handling general exceptions. But it is not the recommended way of dealing with exception, It is advised that whenever possible to state what kind of exception you think might be thrown from the code segment.

 

Example:

The code could be re-written to catch specific exception as follow. Notice that this time we are not using Exception type but we use ZeroDivisionError (Inorder to catch specific exception)

>>> try:
...     a = 10
...     b = 89
...     total = 0
...     avg = (a + b) / total
... except ZeroDivisionError as error:
...     print(str(error))
... 
division by zero
>>> 

 

What if there is possibility of occurrence of different exceptions?

There are time when a particular code segment can go through different kind of exception objects.

When that is likely to happen you can have multiple except block or you can place all Exceptions type which are likely to occur in a bracket.

Examples:

>>> try:
...     a = 4
...     print("The value is" + a)
...     print(a/5)
... except ZeroDivisionError:
...     print("Zero division error occured")
... except (ValueError, TypeError):
...     print("Other error occured")
... 
Other error occured
>>> 

Other way of catching Exception without using Except class

Finally keyword:

Python like most other programming languages have a support (finally keyword) during exception handling. This means the code which is placed on the finally block will execute no matter what happened.

Finally block as shown on the example bellow is placed after the except block to indicate what should happen regardless of occurrence of exceptions.

try:
   a - 2
   print(2 / 0)
except ZeroDivisionError:
   print("Some error occured")
finally:
   print("Either way this run")

 

Raise Exceptions - Throwing exceptions in python:

Python raise keyword can be used to raise different kind of exceptions ( raise is the same as throw keyword in other languages like java)

 

print("hello world")

raise ValueError

 

When you use the raise keyword you pass the exception object. Most exceptions objects in python accept string during creation. The string passed is used to give more information about the raised exception.

print("hello world")

raise ValueError("Exception message here")

 

While using try except, raise keyword can be used on the except block to raise whatever exception which occurred.

try:
  a = 12
  c = 0
  print(a / c)
except ZeroDivisionError:
  raise ValueError

 

I hope this article gave you some information concerning exceptions in python. For more python exception handling examples please visit More on exception

 

Conclussion:

Its crucial that you understand exception handling in while programming and not just to python. Having a good knowledge on them will guarantee that single failure doesnt block the whole application. Please dont forget to like subscribe and follow @bongobinary social account on twiter, facebook, instagram and youtube.

 

Related articles:

How to install python 3.8 on ubuntu    How to install python 3.8 on ubuntu
What is new in python 3.8    Whats new in python