If there is an error in the code and an error occurs when you [compile] the program (http://e-words.jp/w/E382B3E383B3E38391E382A4E383AB.html), it is called a "compile error". Even if the compilation ends normally, if something goes wrong during the execution, it is called an exception. In my article, I used to use the word "error" to express "exception" so that the meaning could be conveyed. From now on, we will use the correct word "exception".
The exceptions introduced in the previous articles were as follows.
Another notable code that raises an exception is division by zero, which divides a number by zero.
division_by_zero.py
a = 10 / 0
print("{0}".format(a))
The above program does not raise an error at compile time, but raises an exception at runtime as shown below.
ZeroDivisionError: integer division or modulo by zero
Writing "if an exception occurs" in the code where an exception can occur is called exception handling.
I don't want the program to quit suddenly while it's running. Therefore, modify the division by zero program written above so that an exception does not occur at runtime.
division_by_zero2.py
try:
a = 10 / 0
print("{0}".format(a))
except ZeroDivisionError:
print("ZeroDivisionError!!")
Enclose the code that can cause an exception in ** try: **. Then, the processing when an exception occurs is enclosed in ** except * exception type *: **. The "exception type" must be an appropriate one. For example, in the above program, instead of ZeroDivisionError (= division by zero exception) If you specify ValueError (= an exception that stores a value that does not match the variable type) as shown below, the exception will not be caught.
division_by_zero_EXCEPTION2.py
try:
a = 10 / 0
print("{0}".format(a))
except ValueError:
print("ZeroDivisionError!!")
I get an exception when I run the above program.
In the previous program, when an exception occurred, I created a message to output by myself, You can use this because Python retains information when an exception occurs. Try running the following program.
py3.division_by_zero_info.py
try:
a = 10 / 0
print("{0}".format(a))
except ZeroDivisionError as e:
print("type:{0}".format(type(e)))
print("args:{0}".format(e.args))
print("message:{0}".format(e.message))
print("{0}".format(e))
You can define a variable with error information by writing ** exception * exception type * as * variable *: **. The output result is as follows. You may want to output these instead of your own messages.
type:<type 'exceptions.ZeroDivisionError'> args:('integer division or modulo by zero',) message:integer division or modulo by zero integer division or modulo by zero
As I mentioned earlier, the "exception type" must be described appropriately, but there are multiple patterns of exceptions. If it occurs, you can write more than one like the branch elif.
try:
f = open(file_name,'w')
data = dict_input['data']
f.write(data)
f.close()
except KeyError:
print('Key not found')
except (FileNotFoundError, TypeError) :
print('The file could not be opened')
except:
print('Some kind of error has occurred')
This is part of the processing of the program that opens the file, but the file input and output I won't explain the detailed code because it will not be explained in "Python Basic Course". Look at the ** except KeyError **, ** except (FileNotFoundError, TypeError) **, ** except ** parts. If an exception occurs in the try clause, Python first checks to see if the exception can be caught with a KeyError. If possible, output "Key not found". If it cannot be caught by KeyError, check if it can be caught by FileNotFoundError or TypeError. Supplement If possible, output "The file could not be opened". In this way, it is possible to perform the same processing for multiple exceptions. If it still fails to catch, the last except means "all exceptions". It has the same meaning as the else of the branch. When it reaches this point, it outputs "Some error has occurred".
If you prepare only except: without writing multiple exceptions, all exceptions will be caught, but If you catch all exceptions with the same except clause, it will be difficult to understand the cause of the exception. It's a good idea to write each exception type and then write except: at the end.
else/finally else executes the process "when the process proceeds to the end without raising an exception in the try clause". finally executes the process "finally, regardless of the occurrence of an exception".
try_else_finally.py
try:
a = 10 / 0
# a = 10 / 1
print("{0}".format(a))
except ZeroDivisionError as e:
print("ZeroDivisionError!!")
else:
print("else statement")
finally:
print("finally statement")
Run the above program. Then comment out a = 10/0 and uncomment a = 10/1 below. Try again and make sure both outputs are as described.
raise You can use raise to deliberately raise an exception. ** raise ** * Describe the exception you want to raise (exception you want to send) * in the place where you want to raise the exception. Return an exception by writing raise in the except clause. After executing the following program, comment out raise in the except clause and check the difference in operation between the two.
raise.py
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
That concludes the explanation of the exception.
Next: Python Basic Course (12 Functions)
Recommended Posts