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.
If you let the exception propagate all the way up to the main() method, the program will end.
finally ..." in Python. In Python, try and except are used to handle exceptions (= errors detected during execution). With try and except , even if an exception occurs, the process continues without terminating. You can use else and finally to set the ending process.
The exit () function is used to break out of a loop. This function causes an immediate termination of the entire program done by the operation system.
Handling an exception. If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.
You want to partially handle an exception before passing it on for more handling. In the following example, a catch block is used to add an entry to an error log before rethrowing the exception. try { // Try to access a resource. } catch (UnauthorizedAccessException e) { // Call a custom error logging procedure.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc. The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario:
IOW : you don't have to do anything to make your script exit when an exception happens. Show activity on this post. Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.
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
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