Difference between revisions of "Python - Exception Handling"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) |
PeterHarding (talk | contribs) |
||
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> |
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