Difference between revisions of "Python - Exception Handling"

From PeformIQ Upgrade
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 2: Line 2:


=Examples=
=Examples=
<pre>
  try:
      f  = open(log_file, 'r')
  except IOError, e:
      sys.stderr.write('open() failed -> %s\n' % e)
      sys.exit(1)
</pre>


<pre>
<pre>
Line 44: Line 52:


<pre>
<pre>
  try:
      ...
  except:
      ...
  finally:
      os.chdir(root)
</pre>
</pre>


<pre>
  try:
      # Fork a child process so the parent can exit.  This will return control
      # to the command line or shell.  This is required so that the new process
      # is guaranteed not to be a process group leader.  We have this guarantee
      # because the process GID of the parent is inherited by the child, but
      # the child gets a new PID, making it impossible for its PID to equal its
      # PGID.
      pid = os.fork()
  except OSError, e:
      return((e.errno, e.strerror))    # ERROR (return a tuple)
</pre>


=Exceptions=
=Exceptions=
Here are some common exception values:


* AttributeError
* AttributeError
* IOError
* IOError
* KeyError
* KeyboardInterrupt
* ValueError
* ValueError
* KeyError




[[Category:Python]]
[[Category:Python]]

Latest revision as of 16:01, 31 May 2008

Overview

Examples

   try:
      f  = open(log_file, 'r')
   except IOError, e:
      sys.stderr.write('open() failed -> %s\n' % e)
      sys.exit(1)
   try:
      out = open(data_file, 'w')
   except: 
      print "XXX"
      sys.exit(0)
   try:
      pf = open(pickle_file, "r")
   except IOError, msg:
      sys.stderr.write('[XXX]  %s - Cannot open: %s\n' % (pickle_file, msg))
      details = defaults
      return
   try:
      ifd = open(source_fname, 'r')
   except IOError, e:
      sys.stderr.write('[scramble]  Open failed: ' + str(e) + '\n')
      sys.exit(1)
   try:
      sys.exit(main())
   except KeyboardInterrupt, e:
      print "[skel]  Interrupted!"
   try:
      opts, args = getopt.getopt(sys.argv[1:], "dD:i:s:vV?")
   except getopt.error, msg:
      print __doc__
      return 1
   try:
      ...
   except:
      ...
   finally:
      os.chdir(root)
   try:
      # Fork a child process so the parent can exit.  This will return control
      # to the command line or shell.  This is required so that the new process
      # is guaranteed not to be a process group leader.  We have this guarantee
      # because the process GID of the parent is inherited by the child, but
      # the child gets a new PID, making it impossible for its PID to equal its
      # PGID.
      pid = os.fork()
   except OSError, e:
      return((e.errno, e.strerror))     # ERROR (return a tuple)

Exceptions

Here are some common exception values:


  • AttributeError
  • IOError
  • KeyError
  • KeyboardInterrupt
  • ValueError