5.06.2022 16:04 10.
exception_handling_python - Jupyter Notebook
Python Tutorial
Created by Mustafa Germec, PhD
10. Exception Handling in Python
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of
the program's instructions.
In general, when a Python script encounters a situation that it cannot cope with, it raises an exception.
An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.
If you have some 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, include an except: statement, followed by a block of code which handles the problem
as elegantly as possible.
Common exceptions
ZeroDivisionError
NameError
ValueError
IOError
EOFError
IdentationError
ZeroDivisionError
In [1]:
1 # If a number is divided by 0, it gives a ZeroDivisionError.
2 try:
3 1/0
4 except ZeroDivisionError:
5 print('This code gives a ZeroDivisionError.')
6
7 print(1/0)
This code gives a ZeroDivisionError.
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/3605061481.py in <module>
5 print('This code gives a ZeroDivisionError.')
----> 7 print(1/0)
ZeroDivisionError: division by zero
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 1/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [2]:
1 nlis = []
2 count = 0
3 try:
4 mean = count/len(nlis)
5 print('The mean value is', mean)
6 except ZeroDivisionError:
7 print('This code gives a ZeroDivisionError')
8
9 print(count/len(nlis))
This code gives a ZeroDivisionError
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/2225123637.py in <module>
7 print('This code gives a ZeroDivisionError')
----> 9 print(count/len(nlis))
ZeroDivisionError: division by zero
In [3]:
1 # The following code is like 1/0.
2 try:
3 True/False
4 except ZeroDivisionError:
5 print('The code gives a ZeroDivisionError.')
6
7 print(True/False)
The code gives a ZeroDivisionError.
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/3531407864.py in <module>
5 print('The code gives a ZeroDivisionError.')
----> 7 print(True/False)
ZeroDivisionError: division by zero
NameError
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 2/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [4]:
1 nlis = []
2 count = 0
3 try:
4 mean = count/len(nlis)
5 print('The mean value is', mean)
6 except ZeroDivisionError:
7 print('This code gives a ZeroDivisionError')
8
9 # Since the variable 'mean' is not defined, it gives us a 'NameError
10 print(mean)
This code gives a ZeroDivisionError
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/1642249892.py in <module>
9 # Since the variable 'mean' is not defined, it gives us a 'NameError
---> 10 print(mean)
NameError: name 'mean' is not defined
In [5]:
1 try:
2 y = x+5
3 except NameError:
4 print('This code gives a NameError.')
5
6 print(y)
This code gives a NameError.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/115043188.py in <module>
4 print('This code gives a NameError.')
----> 6 print(y)
NameError: name 'y' is not defined
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 3/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [6]:
1 # Define a function giving a NameError
2 def addition(x, y):
3 z=x+y
4 return z
5
6 print('This function gives a NameError.')
7 total = add(3.14, 1.618)
8 print(total)
This function gives a NameError.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/3845321401.py in <module>
6 print('This function gives a NameError.')
----> 7 total = add(3.14, 1.618)
8 print(total)
NameError: name 'add' is not defined
In [7]:
1 # Since 'Mustafa' is not defined, the following code gives us a 'NameError.'
2 try:
3 name = (Mustafa)
4 print(name, 'today is your wedding day.')
5 except NameError:
6 print('This code gives a NameError.')
7
8 name = (Mustafa)
9 print(name, 'today is your wedding day.')
This code gives a NameError.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/367854978.py in <module>
6 print('This code gives a NameError.')
----> 8 name = (Mustafa)
9 print(name, 'today is your wedding day.')
NameError: name 'Mustafa' is not defined
IndexError
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 4/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [8]:
1 nlis = [0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729]
2 try:
3 nlis[10]
4 except IndexError:
5 print('This code gives us a IndexError.')
6
7 print(nlis[10])
This code gives us a IndexError.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/4262347625.py in <module>
5 print('This code gives us a IndexError.')
----> 7 print(nlis[10])
IndexError: list index out of range
In [9]:
1 # You can also supplytake this error type with tuple
2 tuple_sample = (0.577, 1.618, 2.718, 3.14, 6, 28, 37, 1729)
3 try:
4 tuple_sample[10]
5 except IndexError:
6 print('This code gives us a IndexError.')
7
8 print(tuple_sample[10])
This code gives us a IndexError.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/3170854299.py in <module>
6 print('This code gives us a IndexError.')
----> 8 print(tuple_sample[10])
IndexError: tuple index out of range
KeyError
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 5/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [10]:
1 dictionary = {'euler_constant': 0.577, 'golden_ratio': 1.618}
2 try:
3 dictonary = dictionary['euler_number']
4 except KeyError:
5 print('This code gives us a KeyError.')
6
7 dictonary = dictionary['euler_number']
8 print(dictonary)
This code gives us a KeyError.
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5432/669363184.py in <module>
5 print('This code gives us a KeyError.')
----> 7 dictonary = dictionary['euler_number']
8 print(dictonary)
KeyError: 'euler_number'
You can find more Error Types (https://docs.python.org/3/library/exceptions.html?
utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=N
SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-
2021-01-01) from this connection.
Exception Handling
try/except
In [11]:
1 try:
2 print(name)
3 except NameError:
4 print('Since the variable name is not defined, the function gives a NameError.')
Since the variable name is not defined, the function gives a NameError.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 6/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [1]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 print('This process is running with value = ', value)
8 except:
9 print('This process is not running.')
The entered value is 3.14
The entered value is 0.577
This process is running with value = 5.441941074523397
Multiple Except Blocks
try/except/except etc.
In [2]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 print('This process is running with value = ', value)
8 except ZeroDivisionError:
9 print('This function gives a ZeroDivisionError since a number cannot divide by 0.')
10 except ValueError:
11 print('You should provide a number.')
12 except:
13 print('Soething went wrong!')
The entered value is 2.718
The entered value is 0.0
This function gives a ZeroDivisionError since a number cannot divide by 0.
try/except/else
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 7/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [3]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 except ZeroDivisionError:
8 print('This function gives a ZeroDivisionError since a number cannot divide by 0.')
9 except ValueError:
10 print('You should provide a number.')
11 except:
12 print('Soething went wrong!')
13 else:
14 print('This process is running with value = ', value)
The entered value is 37.0
The entered value is 1.618
This process is running with value = 22.867737948084052
try/except/else/finally
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 8/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [5]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 except ZeroDivisionError:
8 print('This function gives a ZeroDivisionError since a number cannot divide by 0.')
9 except ValueError:
10 print('You should provide a number.')
11 except:
12 print('Soething went wrong!')
13 else:
14 print('This process is running with value = ', value)
15 finally:
16 print('The process is completed.')
The entered value is 1.618
The entered value is 0.577
This process is running with value = 2.8041594454072793
The process is completed.
Multiple except clauses
In [6]:
1 num1 = float(input('Enter a number:'))
2 print('The entered value is', num1)
3 try:
4 num2 = float(input('Enter a number:'))
5 print('The entered value is', num2)
6 value = num1/num2
7 except (ZeroDivisionError, NameError, ValueError): #Multiple except clauses
8 print('This function gives a ZeroDivisionError, NameError or ValueError.')
9 except:
10 print('Soething went wrong!')
11 else:
12 print('This process is running with value = ', value)
13 finally:
14 print('The process is completed.')
The entered value is 3.14
The entered value is 0.0
This function gives a ZeroDivisionError, NameError or ValueError.
The process is completed.
Raising in exception
Using the 'raise' keyword, the programmer can throw an exception when a certain condition is reached.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_notebo… 9/10
5.06.2022 16:04 10. exception_handling_python - Jupyter Notebook
In [7]:
1 num = int(input('Enter a number:'))
2 print('The entered value is', num)
3 try:
4 if num>1000 and num %2 == 0 or num %2 !=0:
5 raise Exception('Do not allow to the even numbers higher than 1000.')
6 except:
7 print('Even or odd numbers higher than 1000 are not allowed!')
8 else:
9 print('This process is running with value = ', num)
10 finally:
11 print('The process is completed.')
The entered value is 1006
Even or odd numbers higher than 1000 are not allowed!
The process is completed.
localhost:8888/notebooks/Desktop/PROGRAMMING_WEB DEVELOPMENT/PYTHON_TUTORIAL/01. python_files_for_sharing/jupyter_noteb… 10/10