Python exception handling (Python learning memo ⑥)

Handling exceptions

point

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("The data cannot be converted to an integer.")
except:
    print("unexpected error: ", sys.exc_info()[0])
    raise #Rethrow the exception so that the caller can catch it

Catch multiple types of exceptions


except(RuntimeError, TypeError, NameError):
    pass

Added else clause


import sys

try:
    f = open('myfile.txt')
    s = f.readline()
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("The data cannot be converted to an integer.")
except:
    print("unexpected error: ", sys.exc_info()[0])
    raise #Rethrow the exception so that the caller can catch it
else:
    print(s)
    f.close()

Make an exception

point

Define an exception

point

Exception class



class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
    
try:
    raise MyError(2*2)
except MyError as e:
    print('My exception occurred, value:', e.value)
#output
# My exception occurred, value: 4

raise MyError('oops!')
#output
# Traceback (most recent call last):
#   File ".\exception_class.py", line 12, in <module>
#     raise MyError('oops!')
# __main__.MyError: 'oops!'

Cleanup process with try-finally

point

finally example



def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("Division by zero error")
    else:
        print('answer: ', result)
    finally:
        print('in finally')

divide(2, 1)
#answer:  2.0
# in finally

divide(2, 0)
#Division by zero error
# in finally

divide("2", "1")
# in finally
# Traceback (most recent call last):
#   File ".\divide.py", line 15, in <module>
#     divide("2", "1")
#   File ".\divide.py", line 3, in divide
#     result = x / y
# TypeError: unsupported operand type(s) for /: 'str' and 'str'

Cleanup process with with

point

with open('workfile', 'r') as f:
    read_data = f.read()

print(f.closed)
# True

Recommended Posts

Python exception handling (Python learning memo ⑥)
Python exception handling
Python exception handling
Python class (Python learning memo ⑦)
Python module (Python learning memo ④)
Python, about exception handling
Python memo
python memo
Python memo
python memo
Exception handling
python learning
Python memo
Python memo
Python memo
Python control syntax, functions (Python learning memo ②)
Input / output with Python (Python learning memo ⑤)
Exception handling during Python API communication
Interval scheduling learning memo ~ by python ~
"Scraping & machine learning with Python" Learning memo
I tried to summarize Python exception handling
[Python] Memo dictionary
LPIC201 learning memo
[Python] Learning Note 1
python beginner memo (9.2-10)
Python learning notes
Python numbers, strings, list types (Python learning memo ①)
[Learning memo] Basics of class by python
Django Learning Memo
python beginner memo (9.1)
python learning output
Python learning site
Python Error Handling
[Introduction to Udemy Python3 + Application] 65. Exception handling
★ Memo ★ Python Iroha
Python learning day 4
Pharmaceutical company researchers summarized Python exception handling
boto3 exception handling
Python data structure and operation (Python learning memo ③)
[Python] EDA memo
Python Deep Learning
Python 3 operator memo
Python learning (supplement)
Deep learning × Python
Python timezone handling
[Memo] Machine learning
[My memo] python
Python standard library: second half (Python learning memo ⑨)
Python3 metaclass memo
Python exception handling a little more convenient
[Python] Basemap memo
Python & Machine Learning Study Memo ③: Neural Network
Python & Machine Learning Study Memo ④: Machine Learning by Backpropagation
Module import and exception handling in python
Python beginner memo (2)
Python & Machine Learning Study Memo ⑥: Number Recognition
python learning notes
[Python] Numpy memo
Python standard library: First half (Python learning memo ⑧)
Python & Machine Learning Study Memo ⑤: Classification of irises
Python & Machine Learning Study Memo ②: Introduction of Library