Sitemap

ABOUT PYTHON - EXCEPTION HANDLING

4 min readDec 17, 2021

--

Press enter or click to view image in full size

A program that is created can sometimes stop abnormally (crashed) caused by data type discrepancy either when the input or output process, or it could be caused improper calculation process, e.g. division by zero. A program that good is a program that as much as possible minimize the occurrence of this crash.

Consider the following example function:

def division(a, b):
result = a/b
print('Result : ' + str(result))
division(8, 3)
division(9, 0)
division(3, 4)

In the program, there is a division function (a, b) that displays the results
a/b division.

When the above program is run, it will produce the following display:

Result : 2.6666666666666665
Traceback (most recent call last):
File "C:/Users/danang/Documents/Matkul dalam Seminggu Semester 1/UAS/coba UAS1 protek.py", line 5, in <module>
division(9, 0)
File "C:/Users/danang/Documents/Matkul dalam Seminggu Semester 1/UAS/coba UAS1 protek.py", line 2, in division
result = a/b
ZeroDivisionError: division by zero

Based on the display, we can see that the program crashes with the message
ZeroDivisionError: division by zero while calling division(9, 0). This is due to the process of dividing by zero, which is 9/0.

To prevent the program from crashing or to keep the program running until it’s finished, we can do exception handling. The exception handling process is done by creating a block with the following syntax:

try:
...
...
except [errorMsg]:
...

The try-except block above is used to capture error messages that appear due to a crashed program. After the error message is captured then it is replaced with another process.

So if this try-except is applied to the example program given at the beginning of the discussion then it will be

def division(a, b):
try:
result = a/b
print('Result : ' + str(result))
except ZeroDivisionError:
print('Division by zero')
division(8, 3)
division(9, 0)
division(3, 4)

Output:

Result : 2.6666666666666665
Division by zero
Result : 0.75

The use of try-except above applies to a function. However, it is also possible to try-except applied when the process calls the function as in the following example:

def division(a, b):
result = a/b
print('Result : ' + str(result))
try:
division(8, 3)
division(9, 0)
division(3, 4)
except ZeroDivisionError:
print('Division by zero')

Output:

Result : 2.6666666666666665
Division by zero

There is a difference in appearance compared to the previous program, namely in this case division(3, 4) is not executed because an exception occurs when executing division(9, 0), the program cannot continue the process in the try section.

Get Danang Kurniawan’s stories in your inbox

Join Medium for free to get updates from this writer.

In the example above, the number of exceptions handled by the try-except block is only one.

Next, how to handle more than one exception?

Example:

number1 = int(input('Enter the fisrt number  : '))
number2 = int(input('Enter the second number : '))
result = number1 / number2
print(result)

The program for dividing two integers above has the potential to contain two types of exceptions, namely the input of the two numbers entered is not an integer and it is also a possible division by zero occurs. The following is an example of an exceptional display in the first state if the input is not an integer (integer):

Enter the fisrt number  : 6
Enter the second number : a
Traceback (most recent call last):
File "C:/Users/danang/Documents/Matkul dalam Seminggu Semester 1/UAS/coba UAS1 protek.py", line 2, in <module>
number2 = int(input('Enter the second number : '))
ValueError: invalid literal for int() with base 10: 'a'

Meanwhile, here’s how it looks exception raised when division by zero occurs

Enter the fisrt number  : 6
Enter the second number : 0
Traceback (most recent call last):
File "C:/Users/danang/Documents/Matkul dalam Seminggu Semester 1/UAS/coba UAS1 protek.py", line 3, in <module>
result = number1 / number2
ZeroDivisionError: division by zero

Then how to handle these two types of exceptions? The trick is to write except twice in the try-except block.

try:
...
...
except [errorMsg1]:
...
except [errorMsg2]:
...

So that after being modified using try-except, the program becomes

try:
number1 = int(input('Enter the fisrt number : '))
number2 = int(input('Enter the second number : '))
result = number1 / number2
print(result)
except ZeroDivisionError:
print('Division by zero')
except ValueError:
print('Invalid data input')

Adding more than one “except” can also be used to handle three exceptions, four, and so on.

Case Study 7.1

Write a program that asks for input in the form of two integers. The program output is a number that is the product of the two numbers. The program created must be able to handle input that does not match the data type. If the input provided is not an integer, a warning will appear that the input is invalid.

Answer:

In simple terms the program for the solution of case study 7.1 is as follows:

number1 = int(input('Enter the fisrt number  : '))
number2 = int(input('Enter the second number : '))
result = number1 + number2
print(result)

However, the above program will throw an exception (crashed) when the input is not an integer, for example:

Enter the fisrt number  : me
Traceback (most recent call last):
File "C:\Users\danang\Documents\Matkul dalam Seminggu Semester 1\UAS\coba UAS1 protek.py", line 1, in <module>
number1 = int(input('Enter the fisrt number : '))
ValueError: invalid literal for int() with base 10: 'me'

Therefore, these problems must be handled with exception handling.

try:
number1 = int(input('Enter the fisrt number : '))
number2 = int(input('Enter the second number : '))
result = number1 + number2
print(result)
except ValueError:
print('Invalid data input')

After the above changes, so that if the input is given a value that is not an integer it will “Invalid data input” message appears.

Enter the fisrt number  : me
Invalid data input

--

--

Danang Kurniawan
Danang Kurniawan

Written by Danang Kurniawan

Danang Kurniawan, K3521016, danangkurniawan110@student.uns.ac.id, Sebelas Maret University