# Biệt lệ (exception) và xác nhận (assertion)¶

## Biệt lệ¶

In [2]:
try:
a = int(input('Tell me one number:'))
b = int(input('Tell me another number:'))
print(a/b)
print('Okay')
except:
print('Bug in user input.')
print('Outside')

Tell me one number:abc
Bug in user input.
Outside

In [ ]:
try:
a = int(input('Tell me one number:'))
b = int(input('Tell me another number:'))
print('a/b =', a/b)
print('a+b =', a+b)
except ValueError:
print('Could not convert to a number.')
except ZeroDivisionError:
print('Can\'t divide by zero')
except:
print('Something went very wrong.')
print('Outside')


## Ví dụ¶

In [ ]:
while True:
try:
n = input('Please enter an integer:')
n = int(n)
break
except ValueError:
print('Input not an integer; try again')
print('Correct input of an integer')

In [3]:
data = []

file_name = input("Provide a name of a file of data ")

try:
fh = open(file_name, 'r')
except IOError:
print('cannot open', file_name)
else:
for new in fh:
if new != '\n':
addIt = new[:-1].split(',') #remove trailing \n
finally:
fh.close() # close file even if fail


Provide a name of a file of data Files/testGradesData.py

In [4]:
data

Out[4]:
[['Eric', ' Grimson', ' 80'],
['John', ' Guttag', ' 100'],
['Ana', ' Bell', ' 90'],
['Drew', ' Houston', ' 70'],
['Mark', ' Zuckerberg', ' 75'],
['Bill', ' Gates'],
['Baron', ' von', ' Richthofen', ' 65']]
In [5]:
data = []

file_name = input("Provide a name of a file of data ")

try:
fh = open(file_name, 'r')
except IOError:
print('cannot open', file_name)
else:
for new in fh:
if new != '\n':
addIt = new[:-1].split(',') #remove trailing \n
finally:
fh.close() # close file even if fail

if data:
for student in data:
try:
except IndexError:

Provide a name of a file of data Files/testGradesData.py

In [6]:
gradesData

Out[6]:
[[['Eric', ' Grimson'], [' 80']],
[['John', ' Guttag'], [' 100']],
[['Ana', ' Bell'], [' 90']],
[['Drew', ' Houston'], [' 70']],
[['Mark', ' Zuckerberg'], [' 75']],
[['Bill', ' Gates'], []],
[['Baron', ' von'], [' Richthofen']]]
In [7]:
data = []

file_name = input("Provide a name of a file of data ")

try:
fh = open(file_name, 'r')
except IOError:
print('cannot open', file_name)
else:
for new in fh:
if new != '\n':
addIt = new[:-1].split(',') #remove trailing \n
finally:
fh.close() # close file even if fail

if data:
for student in data:
try:
name = student[0:-1]
except ValueError:

Provide a name of a file of data Files/testGradesData.py

In [8]:
gradesData

Out[8]:
[[['Eric', ' Grimson'], [80]],
[['John', ' Guttag'], [100]],
[['Ana', ' Bell'], [90]],
[['Drew', ' Houston'], [70]],
[['Mark', ' Zuckerberg'], [75]],
[['Bill', ' Gates'], []],
[['Baron', ' von', ' Richthofen'], [65]]]

## Phát sinh biệt lệ¶

In [9]:
def get_ratios(L1, L2):
""" Assumes: L1 and L2 are lists of equal length of numbers
Returns: a list containing L1[i]/L2[i] """
ratios = []
for index in range(len(L1)):
try:
ratios.append(L1[index]/float(L2[index]))
except ZeroDivisionError:
ratios.append(float('NaN')) #NaN = Not a Number
except:
raise ValueError('get_ratios called with bad arg')
return ratios

In [11]:
L1 = [1, 2, 3, 4]
L2 = [5, 6, 7, 8]
get_ratios(L1, L2)

Out[11]:
[0.2, 0.3333333333333333, 0.42857142857142855, 0.5]
In [12]:
L3 = [5, 6, 7]
get_ratios(L1, L3)

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-9-f85f64f90365> in get_ratios(L1, L2)
6         try:
----> 7             ratios.append(L1[index]/float(L2[index]))
8         except ZeroDivisionError:

IndexError: list index out of range

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-12-271128614d92> in <module>()
1 L3 = [5, 6, 7]
----> 2 get_ratios(L1, L3)

<ipython-input-9-f85f64f90365> in get_ratios(L1, L2)
9             ratios.append(float('NaN')) #NaN = Not a Number
10         except:
---> 11             raise ValueError('get_ratios called with bad arg')
12     return ratios

ValueError: get_ratios called with bad arg
In [14]:
L4 = [5, 6, 7, 0]
get_ratios(L1, L4)

Out[14]:
[0.2, 0.3333333333333333, 0.42857142857142855, nan]
In [20]:
def get_stats(class_list):
new_stats = []
for elt in class_list:
new_stats.append([elt[0], elt[1], avg(elt[1])])
return new_stats

#    try:
#    except ZeroDivisionError:

try:
except ZeroDivisionError:
return 0.0

In [21]:
test_grades = [[['peter', 'parker'], [10.0, 5.0, 85.0]],
[['bruce', 'wayne'], [10.0, 8.0, 74.0]],
[['captain', 'america'], [8.0,10.0,96.0]],

no grades data

Out[21]:
[[['peter', 'parker'], [10.0, 5.0, 85.0], 33.333333333333336],
[['bruce', 'wayne'], [10.0, 8.0, 74.0], 30.666666666666668],
[['captain', 'america'], [8.0, 10.0, 96.0], 38.0],
[['deadpool'], [], 0.0]]

## Assertion¶

In [25]:
def avg(grades):

In [26]:
avg([])

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-26-938d6a1744f6> in <module>()
----> 1 avg([])

AssertionError: no grades data