Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python try/except: Showing the cause of the error after displaying my variables

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 ..."  
like image 568
NealWalters Avatar asked Dec 30 '10 05:12

NealWalters


People also ask

How do I see the error in try except in Python?

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.

How can the try except statements handle errors in Python?

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.

How do you catch an instance of a specific exception type in Python?

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.


2 Answers

try:       1 / 0  except Exception as e:      print(e) 
like image 54
Corey Goldberg Avatar answered Sep 22 '22 23:09

Corey Goldberg


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()

like image 40
sahhhm Avatar answered Sep 26 '22 23:09

sahhhm