0

I want to create custom error messages for a function.

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!")    

Essentially, what I want is to get an error message every time a wrong value has been written in the function variables, and I've tried creating these messages based on what I've gathered on the Internet, but it doesn't seem to work.

2
  • 1
    Could you be more specific than "it doesn't seem to work"? Why would you expect e.g. launch_speed>0 to raise an error? Commented Jan 27, 2015 at 23:06
  • I'm building a function that calculates the trajectory of a projectile, so I wouldn't want launch speed to be negative Commented Jan 28, 2015 at 0:21

2 Answers 2

2

You can't use try: except: for everything; for example, launch_speed>0 will not raise an error for negative values. Instead, I think you want e.g.

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

You should also test for and raise more specific errors (see "the evils of except"), e.g.:

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

You can see the list of built-in errors in the documentation.

Sign up to request clarification or add additional context in comments.

3 Comments

So I tried using the second one for num_samples, but even if I input for example 5.5, I will get a result for my function and not an error.
@George you should use raw_input, not input; I have updated the answer accordingly.
@George If you specifically want to throw an error if the user gives you a non-integer, you should do something like user_in = raw_input(); if int(user_in) != float(user_in): raise SomeError("With a custom message"). However it seems more useful to me to just convert it to something usable and use it, only complaining if it's not convertable to int
1

Why not go one step further and build your own exception types? There's a quick tutorial in the docs which could be used something like:

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

In this case the default functionality of Exception is fine, but you may be able to get finer granularity in what you catch by defining extra exceptions.

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)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.