0

I'm kinda new to coding and I'd like to be able to stop the program and if possible throw up a custom error message from within a function

(as in:

def Rounded_square(lots of inputs):
    radius = (calculation)
    if radius < 0:
        stop.program("The radius is negative")

)

3
  • Are you talking about exceptions? Commented Jul 16, 2018 at 10:15
  • 1
    Do you really mean stop or pause? Are you in a GUI environment or command line? What operating system are you using? Commented Jul 16, 2018 at 10:16
  • Sorry I was just abstracting when i wrote the stop thing. Yeah it looks like exceptions were the way to go, thanks everyone (just using the basic spyder interface nothing fancy). Commented Jul 16, 2018 at 10:42

4 Answers 4

2

You want to raise an exception

raise ValueError("radius should be positive")
Sign up to request clarification or add additional context in comments.

2 Comments

The question is not clear enough for this to be a definitive answer.
@PeterWood: probably, seems the most likely option however, and since the OP says he's new to coding, it's worth looking into exceptions
1

To throw a custom error message you can do

raise BaseException("my exception text")

You can view built-in exception types here

alternatively to exit the program you can just call

exit()

Comments

0

import os os.exit("The radius is negative") , the value inside the exit() function will be printed to stderr and the return code will be 1 (thanks to @peter-wood for that revelation) and just before that you can just use print for the message

2 Comments

If anything other than an integer is passed to exit, Python converts it to a string, prints it to stderr, and exits with code 1. See sys.exit
did not know that! , thank you , will edit the answer
0

You can throw exceptions using raise statement in python:

raise Exception('Message') # Exception: Message

It is also possible to create custom exceptions:

class MyException(Exception):
  pass

raise MyException('Message') # MyException: Message

So you should use:

raise TypeError('The radius is negative')

You should read some tutorials, about exceptions: https://www.tutorialspoint.com/python/python_exceptions.htm

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.