在Python中放置自定义错误消息

时间:2015-01-27 23:03:31

标签: python validation python-2.7

我想为函数创建自定义错误消息。

def tr( launch_speed , launch_angle_deg , num_samples ):

#Error displays
   try:
      launch_speed>0
   except:
      raise Exception("Launch speed has to be positive!")   
   try:
      0<launch_angle_deg<90
   except:
      raise Exception("Launch angle has to be 0 to 90 degrees!")    
   try:
      um_samples = int(input())
   except:
      raise Exception("Integer amount of samples!")  
   try:
      num_samples >=2
   except:
      raise Exception("At least 2 samples!")    

基本上,我想要的是每次在函数变量中写入错误的值时都会收到错误消息,并且我尝试根据我在Internet上收集的内容创建这些消息,但它没有似乎工作。

2 个答案:

答案 0 :(得分:2)

您不能将try: except:用于所有内容;例如,launch_speed>0 不会为负值引发错误。相反,我认为你想要,例如。

if launch_speed < 0:  # note spacing, and if not try
    raise ValueError("Launch speed must be positive.")  # note specific error

您还应测试并提出更具体的错误(请参阅"the evils of except"),例如:

try:
    num_samples = int(raw_input())  # don't use input in 2.x
except ValueError:  # note specific error
    raise TypeError("Integer amount of samples!")  

您可以看到内置错误列表in the documentation

答案 1 :(得分:1)

为什么不进一步建立自己的异常类型?有一个快速教程in the docs可以使用类似的东西:

class Error(Exception):
    """Base class for exceptions defined in this module"""
    pass

class LaunchError(Error):
    """Errors related to the launch"""
    pass

class LaunchSpeedError(LaunchError):
    """Launch speed is wrong"""
    pass

class LaunchAngleError(LaunchError):
    """Launch angle is wrong"""
    pass

class SamplesError(Error):
    """Error relating to samples"""
    pass

在这种情况下,Exception的默认功能很好,但您可以通过定义额外的异常来获得更精细的粒度。

if launch_speed < 0:
    raise LaunchSpeedError("Launch speed must be positive")
if 0 <= launch_angle < 90:
    raise LaunchAngleError("Launch angle must be between 0 and 90")
um_samples = input()
try:
    um_samples = int(um_samples)
except ValueError:
    raise SampleError("Samples must be an integer, not {}".format(um_samples))
if um_samples < 2:
    raise SampleError("Must include more than one sample, not {}".format(str(um_samples)))