Python exception handling

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

Sample code

test_exception.py


import sys

zerodiv = len(sys.argv) > 1

try:
    if zerodiv:
        a = 10 / 0
    else:
        a = 10 / 1
    print("answer = {}".format(a))

except ZeroDivisionError as e:
    print("ZeroDivisionError")

else:
    print("else statement")

finally:
    print("finally statement")

Execution result

$ python test_exception.py 
answer = 10
else statement
finally statement
$ python test_exception.py zerodiv
ZeroDivisionError
finally statement

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
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
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)
pip install mysql-Error handling during python
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
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips