Python Basic Course (11 exceptions)

What are exceptions?

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.

Catch exceptions

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.

Use of information about exceptions

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

Catch multiple exceptions

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

Python Basic Course (11 exceptions)
Python basic course (12 functions)
Python Basic Course (7 Dictionary)
Python basic course (2 Python installation)
Python basic course (9 iterations)
Python basic course (6 sets)
Python Basic Course (Introduction)
Python basic course (13 classes)
Python basic course (8 branches)
Python Basic Course (3 Python Execution)
Python basic course (10 inclusion notation)
Python Basic Course (5 List Tuples)
Python Basic Course (1 What is Python)
Python Basic Course (14 Modules and Packages)
RF Python Basic_01
Basic Python writing
Python3 basic grammar
RF Python Basic_02
Python Basic Course (at the end of 15)
Python basic course (4 numeric type / character string type)
Python I'm also basic
Python basic grammar / algorithm
Basic sorting in Python
[python] class basic methods
Python3 cheat sheet (basic)
Python basic grammar (miscellaneous)
Python basic memorandum part 2
python basic on windows ②
Python basic memo --Part 2
Basic Python command memo
Python basic grammar note (4)
Python basic grammar note (3)
Basic knowledge of Python
Python basic grammar memo
OpenCV basic code (python)
Python basic memo --Part 1
python memorandum super basic
Python basic if statement
Python Basic --Pandas, Numpy-
Basic Python 3 grammar (some Python iterations)
Python application: Pandas Part 1: Basic
Refactoring Learned in Python (Basic)
BASIC authentication with Python bottle
Python basic dict sort order
[Python] Using OpenCV with Python (Basic)
Python installation and basic grammar
Python Basic Grammar Memo (Part 1)
Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
Basic Python grammar for beginners
[Python] [SQLite3] Operate SQLite with Python (Basic)
Basic usage of Python f-string
I learned Python basic grammar
Python basic grammar (miscellaneous) Memo (4)
Python (Python 3.7.7) installation and basic grammar
Java and Python basic grammar comparison
Python
Scraping with Selenium in Python (Basic)
Python course for data science_useful techniques
[Python] Basic knowledge used in AtCoder
Type specified in python. Throw exceptions