I got this piece of code that is catching an error. Is it possible to write the error handling inside a function for example and then just reference to it inside the code? The goal would be to have all the error handling in a separate file and just call the class inside the code when needed.
This is the normal way and its working fine
#!/usr/bin/env python3
def main():
try:
x = int("foo")
except ValueError:
print("I cought a ValueError")
if __name__ == '__main__': main()
I would like to try something like this, but is something like this possible? and how is it done in a proper way?:
#!/usr/bin/env python3
#All the error handeling goes here:
def exceptValueError():
except ValueError:
print("I cought a ValueError")
def exceptZeroDivisionError():
except ZeroDivisionError:
print("You cant devide by zero")
#Code goes here
def main():
try:
x = int("foo")
exeptValueError()
if __name__ == '__main__': main()
This gives me:
except ValueError:
^
SyntaxError: invalid syntax
Is it possible to use try and instead of except use a function that contains an except? I assume that is not really possible.
def exeptValueError():
except ValueError:
print("I cought a ValueError")
This won't work because there is no try block before the except block (the try block in main doesn't count).
You could do the following, which would still be close to what you want
def exceptValueError():
print("I caught a ValueError")
def main():
try:
x = int("foo")
except ValueError:
exceptValueError()
Related
What is the best practice to run functions in sequence?
I have 4 functions, if the previous one failed, do not run the following ones. In each function, I set global error and error = 1 when exception occurs. Then in main, I just use if statement to check the value of error. I think there should be a better way to do it.
def main():
engine = conn_engine()
if error == 0:
process_sql()
if error == 0:
append_new_rows_to_prod()
if error == 0:
send_email_log()
The canonical way is to raise an exception within the function. For example:
def process_sql():
# Do stuff
if stuff_failed:
raise ProcessSQLException("Error while processing SQL")
def append_new_rows_to_prod():
# Do other stuff
if other_stuff_failed:
raise AppendRowsException("Error while appending rows")
def main():
engine = conn_engine()
try:
process_sql()
append_new_rows_to_prod()
send_email_log()
except ProcessSQLException, AppendRowsException as e:
# Handle exception, or gracefully exit
In Python, can I use try and except when calling functions from my core function, and error checking that the called functions are succeeding? Is this a good way to structure your script with the core function calling functions and sandwiching them in try/except statements to manage errors? If the called functions throw an error or a False, will the try in the core function manage that?
def core_function():
try:
function_a()
except_Exception as e:
print(e)
try:
function_b()
except Exception as E:
print(e)
def function_a()
#this will error
print 1 + 'a'
return True
def function_b()
print 1 + 1
return True
If the called functions throw an error or a False, will the try in the core function manage that
There are basically two ways a function can report an error. By returning something that indicates an error or by raiseing an exception. try catch block in Python handles the latter. You can do something like that.
def core_function():
try:
if function_a() == False:
raise Exception('function_a failed')
if function_b() == False:
raise Exception('function_b failed')
except Exception as E:
print(e)
Read this for Conventions for error reporting: Exceptions vs returning error codes
In my application I have a lot of conditions under which it is non-sensical to run the app further.
Currently I do something like this:
try:
some_fun()
except Exception as e:
print(f'Some short description: {str(e)}')
sys.exit(1)
There is a lot of boilerplate so I'd like to avoid it. I'm looking for something that would allow me to pass the string Some short description as a parameter and automate handling the exception of any kind.
You can register a custom exception hook:
import sys
def print_and_quit(type, value, traceback):
print("error:", value, file=sys.stderr)
sys.exit("something went wrong...")
def main():
sys.excepthook = print_and_quit
# your app entrypoint here...
if __name__ == "__main__":
main()
Note that the default except hook is already quite similar in behavior (printing a traceback and then exiting non-zero), but this allows to customize to do what you want instead. For example, to send an alert or log the exception to somewhere more useful for monitoring, suppress the traceback dump, exit differently for different types of errors, etc.
You could do this:
def handle(func, desc):
try:
func()
except Exception as e:
print(f'{desc}: {str(e)}')
sys.exit(1)
and use it as:
handle(lambda: 2/0, "some desc")
If you want args:
def handle(func, args, desc):
try:
func(*args)
except Exception as e:
print(f'{desc}: {str(e)}')
exit(1)
and to call this:
handle(lambda arg1: 2/0, ["abc"], "some desc")
which will call the lambda with "abc". Also, as #Talon said:
Instead of having the function take a list of arguments, you can star your args argument and make desc a keyword argument. – Talon
Which you could implement as:
def handle(func, desc, *args)
and call as:
handle(lambda arg1: 2/0, "some desc", "abc")
Though that, #wim's solution is better, as long as you don't need to handle specific exceptions.
You can try using :
import sys
import traceback
def my_exception(s, t):
#print(s) # the traceback is still available but not displayed
if t == "error in code X":
print("Something wrong but not critical\n")
return 0
elif t == "error in code Y":
print("Something critical, need to exit\n")
return 1
return 1
try:
val = int(".")
except:
pass
if my_exception(str(traceback.format_exc()), "error in code X"):
sys.exit(1)
print("I'm still here\n")
try:
val = 0/0
except:
pass
if my_exception(str(traceback.format_exc()), "error in code Y"):
sys.exit(1)
print("I'll never run")
Demo
Hi im currently doing a program like this.
class MyError(Exception):
def __init__(self, text = "Correct")
self.text = text
def __str__(self):
return (self.kod)
class Atom(self):
.
.
.
try:
function()
else:
raise MyError("Incorrect use of function")
def main():
try:
a = Atom()
except:
# Here i want to print the error that was raised
What I think I understand is that the error is raised in an object created in Atom().
But I want to send it to my main program and do the print of the error MyError there.
Is it possible to do this and how should I write it so that the correct text of exception is printed since i will have several different error messages.
If i come to the except statement I would want to get the message "Incorrect use of function" printed.
It seems that you're pretty close:
class MyError(Exception):
def __init__(self, text = "Correct")
self.text = text
def __str__(self):
return (self.kod)
class Atom(self):
.
.
.
try:
function()
except: # try: ... else: raise ... seems a bit funky to me.
raise MyError("Incorrect use of function")
def main():
try:
a = Atom()
except Exception as err: # Possibly `except MyError as err` to be more specific
print err
The trick is that when you catch the error, you want to bind the exception instance to a name using the as clause. Then you can print it, look at it's attributes, re-raise or pretty much do anything you choose with it.
Please note that this code still isn't "clean". Generally, you want to limit exception handling as much as possible -- only catch exceptions that expect to see and that you know how to handle. Otherwise, you can sometimes mask hard to find bugs in your code. Because of this:
try:
do_something()
except:
...
is discouraged (it catches all sorts of things like KeyboardInterrupt and SystemExit) ... Instead:
try:
do_something()
except ExceptionIKnowHowToHandle:
...
is advised.
Firstly, never do a blank except. That will catch all errors, including things like KeyboardInterrupt - so you won't be able to ctrl-c out of your program. Here you should just catch MyError.
The except clause also allows you to assign the actual exception to a variable, which you can then print or do anything else with. So you can do:
try:
...
except MyError as e:
print e.text
I am doing some practice problems from online with python and I have a question about how to stay in a script if an error is raised. For example, I want to read in values from prompt and compare them to a set integer value inside the script. The only problem is that when someone enters something other than a number 'int(value)' (ex. value = 'fs') raises an error and exits the script. I want to have it so if this happens I stay inside the script and ask for another value to be entered at the prompt.
Use try/except.
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
success = false
while not success:
try:
value = raw_input('please enter an integer')
int(value)
success = true
except:
pass
How about catching it?
try:
a = int('aaa')
except ValueError:
print('Still working')
Ah, you just want to catch the error (as long as it isn't final): see http://docs.python.org/tutorial/errors.html for details? Or are you looking for something else?
for this, you use try... except as explained in the python documentation
Read up on the try: except: idiom here
if you are doing it as a function you can do it as a decorator of the function
def retry(func):
def wrapper(*args,**kwargs):
while True:
try:
return func(*args,**kwargs)
except Exception as e:
print(f"{e} running again") # or simply pass
return wrapper
#retry
def myfunction():
if badthinghappend:
raise Error
return something