Python: error handling


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. ## Error handling in Python is done through the use of exceptions that are caught in try blocks and handled in except blocks. If an error is encountered, a TRy block code execution is stopped and transferred down to the except block, as shown in the following syntax:
  2.  
  3. try:
  4. f = open("test.txt")
  5. except IOError:
  6. print "Cannot open file."
  7.  
  8. ## In addition to using an except block after the try block, you can also use the finally block. The code in the finally block will be executed regardless of whether an exception occurs.
  9.  
  10. f = open("test.txt")
  11. try:
  12. f.write(data)
  13. . . .
  14. finally:
  15. f.close()
  16.  
  17. ## You can raise an exception in your own program by using the raise exception [, value] statement. The value of exception is one of the built-in Python exceptions or a custom-defined exception object. The value of value is a Python object that you create to give details about the exception. Raising an exception breaks current code execution and returns the exception back until it is handled. The following example shows how to raise a generic RuntimeError exception with a simple text message value:
  18. raise RuntimeError, "Error running script"

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.