I'm new to Python and struggling with handling self-defined errors. When my code spots the error, I want it to throw an error in red font and take me back to the Python terminal without killing Python.
I came across sys.exit() looking for an answer, but it quits Python completely. Do you know of an alternative that throws back an error in red font and takes me back to the terminal?
This is what I have so far.
import sys def do_something(parameter): if parameter > 100: # quit the function and any function(s) that may have called it sys.exit('Your parameter should not be greater than 100!') else: # otherwise, carry on with the rest of the code
Please let me know if I'm not clear and I'll be happy to provide more details. Thank you all in advance!
To stop code execution in python first, we have to import the sys object, and then we can call the exit() function to stop the program from running. It is the most reliable way for stopping code execution. We can also pass the string to the Python exit() method.
Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.
Use try-except statements. a = [1, 2, 3, 4, 5] for x in xrange(0,5): try: print a[x+1] #this is a faulty statement for test purposes except: exit() print "This is the end of the program." No errors printed, despite the error raised.
Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack.
You have two options (at least).
Using a return
statement:
def do_something(parameter): if parameter > 100: # display error message if necessary return # 'exit' function and return to caller # rest of the code
You can also return soemthing
passing the something
value back to the caller. This can be used to provide a status code for instance (e.g. 0: success, 1: error).
Or a better approach is to raise
an exception:
def do_something(parameter): if parameter > 100: raise ValueError('Parameter should...') # rest of the code try: do_something(101) except ValueError, e: # display error message if necessary e.g. print str(e)
See exceptions in the Python manual.
There are built-in exception classes (like ValueError
above). You can also define your own as follows:
class ParameterError(Exception): pass
You can also add additional code to your custom exception classes to process parameters, display custom error messages, etc...
The built-in exceptions are listed here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With