This section describes Python exception handling.
Exception handling describes what to do if an error occurs while the program is running.
Using try
and ʻexcept`, write as follows.
import pandas as pd
try:
df = pd.read_csv('sample.csv')
except FileNotFoundError:
print('File not found.')
Describe the process that may cause an error (exception) after try
, and the process when an error occurs after ʻexcept. If you write the error type after ʻexcept
, exception handling will be executed when the specified error occurs.
In the example shown here, the processing of the ʻexceptclause is executed only when
FileNotFoundError (exception that the specified file cannot be found) occurs. If nothing is described immediately after ʻexcept
, the processing of the ʻexcept` clause will be executed for all errors, but it will also be processed for unexpected errors, so it is recommended. It will not be.
If you enter ʻelse`, you can describe the process you want to continue if no error occurs.
import pandas as pd
try:
df = pd.read_csv('sample.csv')
except FileNotFoundError:
print('File not found.')
else:
df.to_excel('sample.xlsx', index=False)
In the above example, the same contents as the read file are saved as an Excel file.
You can use finally
to describe what you want to do regardless of whether an error has occurred.
import pandas as pd
try:
df = pd.read_csv('sample.csv')
except FileNotFoundError:
print('File not found.')
finally:
print('finished.')
In the above example, the string finished.
is output at the end regardless of whether the file can be read or not.
Here, I explained about exception handling in Python. It is a good idea to include exception handling when requesting input from the user or connecting to the database.
Recommended Posts