I'm not even sure what the right words are to search for. I want to display parts of the error object in an except block (similar to the err object in VBScript, which has Err.Number and Err.Description). For example, I want to show the values of my variables, then show the exact error. Clearly, I am causing a divided-by-zero error below, but how can I print that fact?
try: x = 0 y = 1 z = y / x z = z + 1 print "z=%d" % (z) except: print "Values at Exception: x=%d y=%d " % (x,y) print "The error was on line ..." print "The reason for the error was ..."
To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.
The Python try… except statement runs the code under the “try” statement. If this code does not execute successfully, the program will stop at the line that caused the error and the “except” code will run. The try block allows you to test a block of code for errors.
Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
try: 1 / 0 except Exception as e: print(e)
If you're expecting a DivideByZero error, you can catch that particular error
import traceback try: x = 5 y = 0 print x/y except ZeroDivisionError: print "Error Dividing %d/%d" % (x,y) traceback.print_exc() except: print "A non-ZeroDivisionError occurred"
You can manually get the line number and other information by calling traceback.print_exc()
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