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
, an exception instance will be passed to ʻerr
.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()
point
raise exception name (argument)
raise
in the except clausepoint
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!'
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'
point
with open('workfile', 'r') as f:
read_data = f.read()
print(f.closed)
# True
Recommended Posts