I will publish what I took notes about error handling in Python. Please refer to the link below for details.
https://docs.python.jp/3/tutorial/errors.html
Python 3.x
There are (at least) two distinct types of errors. They are syntax errors and exceptions.
A syntax error is something that is wrong with Python's syntax. It can also be an external error in the code. Since Python expresses code blocks by indentation, I feel that it is a language that is highly readable and less likely to cause syntax errors.
On the other hand, I think the exception can be an internal error in the code. For example, the following code is correct in Python code, but mathematically strange, isn't it?
test = 10 / 0 # <=It cannot be divided by zero!
In this way, the problem that occurs when the code is executed is an exception.
Syntax errors are automatically detected by the interpreter as it interprets the program, so you can fix the angry part.
But how do you deal with exceptions?
Python provides syntax such as try
and ʻexcept` to handle exceptions.
Let's look at a concrete example.
try:
answer = 10 / 0
except ZeroDivisionError:
print("divided by zero!!!")
There are two points in the above code.
try
clauseclause, specify the
type` of the exception that can occur in the try clause, and execute the processing in that case.In this case, an exception, ZeroDivisionError
, which indicates that division by 0 has been performed, occurs from the try clause, and it is processed under ʻexcept ZeroDivisionError`.
As you can see, use try ~ except
to handle exceptions.
Define a divide
function that takes two numbers as arguments and returns their quotients as follows:
def divide(x, y):
answer = x / y
return answer
It looks good at first glance. However, as we have seen, we need to be careful about division.
When divide (10, 0)
etc. is executed, ZeroDivisionError
will occur.
Let's improve the function as follows, considering the case where 0 is passed as the second argument (0 is passed as a result of calculation instead of literally 0).
import math
def divide(x, y):
try:
answer = x / y
except ZeroDivisionError:
print("numbers cannot be divided by zero!")
answer = math.nan
return answer
Even if you divide it by 0, the program will work for the time being!
But what if you are passed an unexpected argument, such as a string
or a tuple
...
I will not describe the answer here, but try to implement it by keeping the following points in mind.
If you care too much about exceptions, your code can swell and readability, so think on a case-by-case basis.
Even if an exception occurs or you don't get angry, you may want to do something in common. As a concrete example, it's a bit painful, but take a look at the code below.
try:
answer = 10 / 0
except ZeroDivisionError as e:
answer = math.nan
finally:
print(answer)
A new keyword called finally
has appeared.
By using this keyword, the processing specified in the finally
clause will be performed regardless of whether an exception occurs or not.
By the way, ʻas e is used in the ʻexcept
clause, but this is to hold the generated exception object in a variable called ʻe` so that it can be referenced in subsequent blocks.
Therefore, if you change the code as shown below, the contents of the exception will be output.
#abridgement
except ZeroDivisionError as e:
print(type(e)) # => <class 'ZeroDivisionError'>
print(e.args) # => ('division by zero',)
print(e) # => division by zero
In Python, the scope of variables is basically determined by the indentation of the code.
Then, can the variable ʻam_i_visible defined in the following code be referenced in the first
print () `?
try:
am_i_visible = "yes"
except:
do_something()
print(am_i_visible) # => ???
You can refer to the correct answer. I think that yes
is output.
Indentation is used to clarify how far the try
clause is, so you can refer to it in this case.
Python can be a bit confusing in scope ...
In the for
statement below, the variable n
becomes a global variable ...
sum = 0
for n in range(1, 5):
sum = sum + n
print(n) # => 4
It's easy, but I've summarized Python's error handling. Python's exception handling still has a lot to touch on, but that's it.
I'm still new to Python, so if you have any advice, please leave it in the comments.
Recommended Posts