def initiate_security_protocol(code):
if code == 1:
print("Returning onboard companion to home location...")
if code == 712:
print("Dematerializing to preset location...")
code = int(input("Enter security protocol code: "))
initiate_security_protocol(code)
>>> Enter security protocol code: 712
Dematerializing to preset location...
>>> Enter security protocol code: seven one two
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/security_protocols.py", line 7, in <module>
code = int(input("Enter security protocol code: "))
ValueError: invalid literal for int() with base 10: 'seven one two'
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/security_protocols.py", line 7, in <module>
code = int(input("Enter security protocol code: "))
ValueError: invalid literal for int() with base 10: 'seven one two'
我有从下到上阅读这些信息的习惯,因为它可以帮助我首先获得最重要的信息。如果你查看最后一行,你会看到ValueError,这是已引发的特定异常。确切的细节如下;在这种情况下,无法使用 . 将字符串'seven one two'用int()转换为整数。我们还了解到它正在尝试转换为以10 为底的整数,这在其他场景中可能是有用的信息。想象一下,例如,如果那行改成...
ValueError: invalid literal for int() with base 10: '5bff'
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 6, in <module>
decode_message("Bad Wolf")
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 4, in decode_message
initiate_security_protocol(message)
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/security_protocols.py", line 2, in initiate_security_protocol
code = int(code)
ValueError: invalid literal for int() with base 10: 'Bad Wolf'
datafile_index = {
# Omitted for brevity.
# Just assume there's a lot of data in here.
}
def get_datafile_id(subject):
id = datafile_index[subject]
print(f"See datafile {id}.")
get_datafile_id("Clara Oswald")
get_datafile_id("Ashildir")
See datafile 6035215751266852927.
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 30, in <module>
get_datafile_id("Ashildir")
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 26, in get_datafile_id
id = datafile_index[subject]
KeyError: 'Ashildir'
def get_datafile_id(subject):
if subject in datafile_index:
id = datafile_index[subject]
print(f"See datafile {id}.")
else:
print(f"Datafile not found on {subject})
def get_datafile_id(subject):
try:
id = datafile_index[subject]
print(f"See datafile {id}.")
except KeyError:
print(f"Datafile not found on {subject}")
class Tardis:
def __init__(self):
pass
def camouflage(self):
raise NotImplementedError('Chameleon circuits are stuck.')
tardis = Tardis()
tardis.camouflage()
当我们执行该代码时,我们会看到我们引发的异常。
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/tardis.py", line 10, in <module>
tardis.camoflague()
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/tardis.py", line 7, in camoflague
raise NotImplementedError('Chameleon circuits are stuck.')
NotImplementedError: Chameleon circuits are stuck.
Night night
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/byzantium.py", line 18, in <module>
byzantium.gravity_field()
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/byzantium.py", line 8, in gravity_field
raise SystemError("Gravity Failing")
SystemError: Gravity Failing
注意:你可能认为我们需要说except SystemError as e:或者说raise e什么,但那是矫枉过正。对于冒泡的异常,我们只需要自己调用raise。
class SpacetimeError(Exception):
def __init__(self, message):
super().__init__(message)
class Tardis():
def __init__(self):
self._destination = ""
self._timestream = []
def cloister_bell(self):
print("(Ominous bell tolling)")
def dematerialize(self):
self._timestream.append(self._destination)
print("(Nifty whirring sound)")
def set_destination(self, dest):
if dest in self._timestream:
self.cloister_bell()
self._destination = dest
def engage(self):
if self._destination in self._timestream:
raise SpacetimeError("You should not cross your own timestream!")
else:
self.dematerialize()
tardis = Tardis()
# Should be fine
tardis.set_destination("7775/349x10,012/acorn")
tardis.engage()
# Also fine
tardis.set_destination("5136/161x298,58/delta")
tardis.engage()
# The TARDIS is not going to like this...
tardis.set_destination("7775/349x10,012/acorn")
tardis.engage()
显然,最后一个将导致我们的SpacetimeError异常被引发。
让我们再看看那个异常类声明。
class SpacetimeError(Exception):
def __init__(self, message):
super().__init__(message)
def initiate_security_protocol(code):
if code == 1:
print("Returning onboard companion to home location...")
if code == 712:
print("Dematerializing to preset location...")
code = int(input("Enter security protocol code: "))
initiate_security_protocol(code)
>>> Enter security protocol code: 712
Dematerializing to preset location...
>>> Enter security protocol code: seven one two
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/security_protocols.py", line 7, in <module>
code = int(input("Enter security protocol code: "))
ValueError: invalid literal for int() with base 10: 'seven one two'
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/security_protocols.py", line 7, in <module>
code = int(input("Enter security protocol code: "))
ValueError: invalid literal for int() with base 10: 'seven one two'
我有从下到上阅读这些信息的习惯,因为它可以帮助我首先获得最重要的信息。如果你查看最后一行,你会看到ValueError,这是已引发的特定异常。确切的细节如下;在这种情况下,无法使用 . 将字符串'seven one two'用int()转换为整数。我们还了解到它正在尝试转换为以10 为底的整数,这在其他场景中可能是有用的信息。想象一下,例如,如果那行改成...
ValueError: invalid literal for int() with base 10: '5bff'
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 6, in <module>
decode_message("Bad Wolf")
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 4, in decode_message
initiate_security_protocol(message)
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/security_protocols.py", line 2, in initiate_security_protocol
code = int(code)
ValueError: invalid literal for int() with base 10: 'Bad Wolf'
datafile_index = {
# Omitted for brevity.
# Just assume there's a lot of data in here.
}
def get_datafile_id(subject):
id = datafile_index[subject]
print(f"See datafile {id}.")
get_datafile_id("Clara Oswald")
get_datafile_id("Ashildir")
See datafile 6035215751266852927.
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 30, in <module>
get_datafile_id("Ashildir")
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/databank.py", line 26, in get_datafile_id
id = datafile_index[subject]
KeyError: 'Ashildir'
def get_datafile_id(subject):
if subject in datafile_index:
id = datafile_index[subject]
print(f"See datafile {id}.")
else:
print(f"Datafile not found on {subject})
def get_datafile_id(subject):
try:
id = datafile_index[subject]
print(f"See datafile {id}.")
except KeyError:
print(f"Datafile not found on {subject}")
class Tardis:
def __init__(self):
pass
def camouflage(self):
raise NotImplementedError('Chameleon circuits are stuck.')
tardis = Tardis()
tardis.camouflage()
当我们执行该代码时,我们会看到我们引发的异常。
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/tardis.py", line 10, in <module>
tardis.camoflague()
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/tardis.py", line 7, in camoflague
raise NotImplementedError('Chameleon circuits are stuck.')
NotImplementedError: Chameleon circuits are stuck.
Night night
Traceback (most recent call last):
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/byzantium.py", line 18, in <module>
byzantium.gravity_field()
File "/home/jason/Code/FiringRanges/PyFiringRange/Sandbox/byzantium.py", line 8, in gravity_field
raise SystemError("Gravity Failing")
SystemError: Gravity Failing
注意:你可能认为我们需要说except SystemError as e:或者说raise e什么,但那是矫枉过正。对于冒泡的异常,我们只需要自己调用raise。
class SpacetimeError(Exception):
def __init__(self, message):
super().__init__(message)
class Tardis():
def __init__(self):
self._destination = ""
self._timestream = []
def cloister_bell(self):
print("(Ominous bell tolling)")
def dematerialize(self):
self._timestream.append(self._destination)
print("(Nifty whirring sound)")
def set_destination(self, dest):
if dest in self._timestream:
self.cloister_bell()
self._destination = dest
def engage(self):
if self._destination in self._timestream:
raise SpacetimeError("You should not cross your own timestream!")
else:
self.dematerialize()
tardis = Tardis()
# Should be fine
tardis.set_destination("7775/349x10,012/acorn")
tardis.engage()
# Also fine
tardis.set_destination("5136/161x298,58/delta")
tardis.engage()
# The TARDIS is not going to like this...
tardis.set_destination("7775/349x10,012/acorn")
tardis.engage()
显然,最后一个将导致我们的SpacetimeError异常被引发。
让我们再看看那个异常类声明。
class SpacetimeError(Exception):
def __init__(self, message):
super().__init__(message)