[Python of Hikari-] Chapter 07-02 Exception handling (continuous execution of the program by exception handling)

[Python] Chapter 07-02 Continuous execution of programs by exception handling

Chapter 07-01 dealt with two exceptions. However, as we saw in the previous section, if an exception occurs, the program will end on the spot. You need to continue processing this program, or notify the screen that an exception has occurred even if you cannot continue. This time, I will explain ** exception handling ** when an exception occurs.

Description of exception handling

As mentioned above, if an exception occurs, the process will be interrupted. Therefore, in order not to interrupt it, it is necessary to ** execute the process by the program described in another place **. This kind of processing is called ** exception handling **.

Exception handling is roughly described as follows.

try:
Where you want to handle exceptions
except:
Where to handle exceptions

Let's actually write exception handling. Create a file with the file name samp07-02-01.py </ font> in chap07 </ font>, and enter the following code Please write.

samp07-02-01.py


print('Find the division a ÷ b.')

try:
    a = int(input('Enter the value of a:'))
    b = int(input('Enter a value for b:'))
    print(a / b)
except:
    print('Since the division by 0 has been performed, the processing ends.')

[Execution result] </ font> Find the division a ÷ b. Enter the value of a: 10 Enter a value for b: 0 Since the division by 0 has been performed, the processing ends.

This time, in the block of ** try: **, division by 0 is performed, so exception handling occurs. Then, it jumps to the ** except: ** block and the processing in that block is performed.

In Chapter 07-01, ** try-catch ** was not described, so the process was forcibly interrupted and an error message was displayed in red, but this time exception handling occurred. Therefore, no error message has been issued.

In this way, in except, write the processing when an exception occurs. This time, it was output by ** print function **, but it can be used for things like "notify the monitoring terminal" and "prompt processing again".

Certain exceptions

I mentioned ** except ** earlier. This time, on the premise that "0 may be assigned to b", "Since division by 0 was performed, the processing will be terminated" was output in except.

But there are other exceptions. If set to except, exceptions other than division by 0 may occur. For example, if you mistakenly enter characters instead of numbers, the following error will be output. This is the execution result of the previous program samp07-02-01.py </ font>.

[Execution result] </ font> Find the division a ÷ b. Enter the value of a: 10 Enter a value for b: z </ font> Since the division by 0 has been performed, the processing ends.

Looking at this, the letters **'z' ** are in place of ** b **. This is no exception to division by zero. This is an exception to the fact that you put characters where you originally had to enter numbers.

Therefore, if you set ** except **, exception handling will be executed for any exception. In this case, you need to prepare two items, "Exception handling for division by 0" and "Exception handling when entering characters". Each of these is a specific exception, and you need to handle the exception for each.

As you can see by looking at the URL below, there are quite a few specific exceptions.

https://docs.python.org/ja/3/library/exceptions.html#concrete-exceptions

There is also a description on the above site, but this time, "Exception handling of division by 0" is ** ZeroDivisionError , "Exception handling when entering characters" is ** "When entering characters" Exception handling " is used. Create a file with the file name samp07-02-02.py </ font> in chap07 </ font>, and enter the following code Please write.

samp07-02-02.py


print('Find the division a ÷ b.')

try:
    a = int(input('Enter the value of a:'))
    b = int(input('Enter a value for b:'))
    print(a / b)
except ZeroDivisionError:
#Exception handling when the value of b meets 0
    print('Since the division by 0 has been performed, the processing ends.')
except ValueError:
#Exception handling when a or b is not a number
    print('Since non-numeric data has been entered, processing ends.')

[Execution result 1] </ font> Find the division a ÷ b. Enter the value of a: 10 Enter a value for b: 0 Since the division by 0 has been performed, the processing ends.

[Execution result 2] </ font> Find the division a ÷ b. Enter the value of a: 10 Enter a value for b: z Since non-numeric data has been entered, processing ends.

I will follow the process in order. First, regarding the exception in the case of division by 0, the above URL has the following description.

exception ZeroDivisionError Sent when the second argument of division or modulo operation is 0. The associated value is a string that indicates the operand and operator type in the operation.

In the first [Execution result 1], 0 is assigned as the value of ** b **, so an exception occurs and the exception handling on the ZeroDivisionError side is performed.

exception ValueError It is thrown when an operator or function receives an argument of the correct type but with an incorrect value, or in situations where it cannot be described by a more detailed exception such as IndexError.

In [Execution result 2],'z' is assigned as the value of ** b **, an exception occurs because division cannot be performed, and exception handling on the ValueError side is performed.

Practice problem

We have prepared exercises. Please try to solve it. Create the program in chap07 </ font>. You can specify any variable name you like. [1] [Chapter 07-01](https://qiita.com/ko0821/items/4df28c2d6a2392f9bcb7#%E4%BE%8B%E5%A4%96%E3%83%AA%E3%82%B9%E3 % 83% 88% E3% 81% AE% E8% A6% 81% E7% B4% A0% E3% 82% 92% E8% B6% 85% E3% 81% 88% E3% 81% A6% E6% 8C % 87% E5% AE% 9A% E3% 81% 97% E3% 81% 9F% E5% A0% B4% E5% 90% 88% E3% 81% AE% E4% BE% 8B% E5% A4% 96 ) Written in the following program, </ font>

ls = [1, 3, 5, 7, 9]
print(ls)
i = int(input('Please specify the element number in the above list:'))

print(ls[i])

For <font color = # 3333ff>, create a program that raises exception handling when the specified number of elements is exceeded. In addition, please create it by the method using a specific exception. Let's check the specific exception at the above URL. </ font>

[Execution result] </ font> [1, 3, 5, 7, 9] Please specify the element number in the above list: 5 It is specified beyond the elements of the list.

Finally

Keep in mind that exception handling is one way to make an error-resistant program. Exception handling does not cause an error in the program, so be sure to wear it to prevent serious incidents. It will appear frequently in the future.

Return to [Table of Contents Link]

Recommended Posts