Python exception handling

Typical exception

TypeError Example: TypeError: unsupported operand type (s) for /:'str' and'int' Error that occurs when trying to calculate the String type

ZeroDivisionError Example: ZeroDivisionError: division by zero Error that occurs when dividing by zero like 1/0

NameError Example: NameError: name'hoge' is not defined Error when using undefined variables

AttributeError Example: AttributeError: type object ‘list’ has no attribute ‘fuga’ Error when trying to access a non-existent attribute

Python exception handling rules

--try: Exception handling of enclosed code --ʻExcept : Block to be executed when an error-case exception occurs --ʻExcept: Block to execute when any exception occurs --ʻElse: Block to execute only if no exception occurs --finally`: Block to execute with or without an exception

try-except Used when you want to continue the process even if an error is derived from the executed process.


Num = [1,2,3]
n = 4

#Extract errors while continuing processing
try:
    print(Num[n])  
except:
    print('error')  #データがない場合、error

print('Continue processing')

#Output result
error
Continue processing

Other exception handling

If there are multiple exceptions, the processing is divided according to the type of exception.

Num = [1,2,3,4]
n = 5
n = 'String'   

try:
    print(Num[n])
except IndexError as ie:
    print('error contents: {}'.format(ie))
except NameError as ne:
    print(ne)
except Exception as ex: #When an error other than IndexError and NameError occurs
    print('error contents: {}'.format(ex))

print('Exception occurred')

#Output result
error contents: list indices must be integers or slices, not str
Exception occurred

finaly Even if an error occurs, always execute the following processing in finaly

Num = [1,2,3,4]
n = 5
n = 'String'   

try:
    print(Num[n])
except IndexError as ie:
    print('error contents: {}'.format(ie))
except NameError as ne:
    print(ne)
except Exception as ex: #When an error other than IndexError and NameError occurs
    print('error contents: {}'.format(ex))
finally:    #← Process that you definitely want to execute
    print('Must be executed')

print('Exception occurred')

#Output result
error contents: list indices must be integers or slices, not str
Must be executed
Exception occurred

raise and pass

Use raise if you want to intentionally raise an error

try:
    raise TypeError
except:
    print('Intentionally generate an error')

Recommended Posts

Python exception handling
Python exception handling
Python, about exception handling
Exception handling
Python exception handling (Python learning memo ⑥)
Exception handling during Python API communication
Python Error Handling
boto3 exception handling
Python timezone handling
I tried to summarize Python exception handling
[Introduction to Udemy Python3 + Application] 65. Exception handling
Pharmaceutical company researchers summarized Python exception handling
Python exception handling a little more convenient
Module import and exception handling in python
Handling yaml with python
Handling json in python
Exception message in Python
Python decimal point handling
Hexadecimal handling in Python 3
Python exception class list
Fizzbuzz with exception handling
Python
[Python for Hikari-] Chapter 07-01 Exception Handling (Errors and Exceptions)
Exception handling using Python's ZeroDivisionError
python> Handling of 2D arrays
Handling of python on mac
Relative url handling in python
Handling of sparse tree-structured attributes (Python)
Python Application: Data Handling Part 3: Data Format
Python class definitions and instance handling
Handling of JSON files in Python
Handling timezones in Python (datetime, pytz)
Show stack trace with python exception
Handling regular expressions with PHP / Python
[Python of Hikari-] Chapter 07-02 Exception handling (continuous execution of the program by exception handling)
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
Python memo
Python comprehension
Python Singleton
Python basics ④
Python Memorandum 2
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative