Python Error Handling

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

environment

Python 3.x

What is Error?

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.

Confront Error

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.

  1. Execute code that can cause exceptions in the block of the try clause
  2. In the block of the ʻexceptclause, specify thetype` 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.

Various use cases

Supports function execution

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.

  1. What kind of exception type is thrown when the operation cannot be performed correctly
  2. Is it likely that correct follow-up to exceptions (handling in the except clause) will be required?

If you care too much about exceptions, your code can swell and readability, so think on a case-by-case basis.

Inserts common processing regardless of whether an exception occurs

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

What is the scope of variables?

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

Finally

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

Python Error Handling
Mainframe error handling
Python exception handling
SikuliX error handling
Python timezone handling
django.db.migrations.exceptions.InconsistentMigrationHistory error handling
Python exception handling
Handling yaml with python
About tweepy error handling
Handling json in python
Python Not Implemented Error
Today's python error: killed
Python error list (Japanese)
Python, about exception handling
Python decimal point handling
Error handling in PythonBox
Hexadecimal handling in Python 3
GraphQL (gqlgen) error handling
Around feedparser error handling
[Python] for statement error
[Error countermeasures] django-heroku installation error handling
Error handling when installing mecab-python
Python exception handling (Python learning memo ⑥)
About FastAPI ~ Endpoint error handling ~
Python
[Python] SQLAlchemy error avoidance memorandum
python> Handling of 2D arrays
Handling of python on mac
[youtube-dl] python3 SSL error (CERTIFICATE_VERIFY_FAILED)
Error when playing with python
#python Python Japanese syntax error avoidance
Slice error in python (´ ; ω ; `)
PyCUDA build error handling memorandum
Relative url handling in python
Error resolution python version check
[python] Error when installing library ramkan
Today's python error: SyntaxError Non-ASCII character
Handling of sparse tree-structured attributes (Python)
Error when building mac python environment
Python error: ModuleNotFoundError: No module named'flask'
pip install mysql-Error handling during python
Python class definitions and instance handling
Exception handling during Python API communication
Handling of JSON files in Python
[Error handling] peewee.IntegrityError 1451 occurs in peewee
A pretty sloppy Python error solution
Handling timezones in Python (datetime, pytz)
Today's python error: image is blank
Python error detection run from Powershell
Error handling when updating Fish shell
Handling regular expressions with PHP / Python
Strange and horrifying Python error story
kafka python
I tried to summarize Python exception handling
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
[Python] Name Error: name'urlparse' is not defined
Python comprehension
Python technique