This artcie mentions small esample of handling exceptions in python
You can write a program such as sorting and processing exceptions. Please see the following example. In this example, but prompts the user for input until a valid string is entered, the user program (Control-C or using the operating system that supports key or some) programs over the interrupt We may be able to disrupt; user-generated interrupts, KeyboardInterrupt Please note that you will be notified that an exception is thrown.
>>> while True:
… try:
… x = int(raw_input(“Please enter a number: “))
… break
… except ValueError:
… print “Oops! That was no valid number. Try again…” .
…
The try statement works as follows.
* First, try clause (try clause) (statements between try and except keywords) is executed.
* The exception to anything, except try to skip the section concludes the statement.
* try exception occurs when you try running in the clause, the rest of that clause is skipped. Second, except when an exception type that matches the exception is specified after the keyword, except clause was executed after, try the sentence will continue to run after the section.
* except Moshimo except when an exception does not match the exceptions specified in the clause, the exception is passed to the outside of the try statement. Handler for the exception (handler, processing unit) With no where, an unhandled exception (unhandled exception) Nearby, stop the run with a message like the one shown above.
One more try statements except to set up a section, you can specify handlers for different exceptions. Be run at no more than one handler. Try corresponding to the handler only handle exceptions that occur in the clause, the same exception occurred in try in another exception handler does not process clause. except except the section can be passed to the tuple several exceptions enclosed in parentheses. For example, do the following:
… except (RuntimeError, TypeError, NameError):
… pass
Last name except in the exception clause is omitted, a wildcard (wildcard, symbol collectively) can make. Please use the wildcard section except very carefully. That is, a wildcard is easily hiding the error from the normal program. The wild card will be dispatched after the exception clause except after printing an error message (to be able to handle exceptions to the caller as well as functions or methods) can be used in applications:
import sys import sys
try:
f = open(‘myfile.txt’)
s = f.readline()
i = int(s.strip())
except IOError, (errno, strerror):
print “I/O error(%s): %s” % (errno, strerror)
except ValueError:
print “Could not convert data to an integer.”
except:
print “Unexpected error:”, sys.exc_info()[0] print “Unexpected error:”,
raise
try … except statement has an optional else clause (else clause) can be set up. else if you set up a section, all except clauses must?Kane than behind. except clause, try to help write the code to be executed when no exception is thrown in the section entirely. For example, do the following:
for arg in sys.argv[1:]:
try:
f = open(arg, ‘r’)
except IOError:
print ‘cannot open’, arg
else:
print arg, ‘has’, len(f.readlines()), ‘lines’
f.close()
Add to add the code behind the section rather than try else clause is better. Because, in doing so try … except to avoid the situation because that would be a chance to catch an exception thrown from the code other than the one you want to protect statement.
When an exception occurs, you can have a value associated with this exception.
except in the section, the name of an exception (exception name or tuple) can be specified after the variable. This variable is tied to the exception instance, instance.args contains an exception to the argument at instantiation. The exception instance defines __getitem__ and __str__ and .args are promoted or convenient to be able to access or print directly without reference to the argument.
args is not recommended for use. Instead, the arguments passed to please only one exception (if you need more than one value can be a tuple). And that message combines attributes. Not only raise an exception when instantiation before, attributes can be added if necessary.
>>> try:
… raise Exception(’spam’, ‘eggs’)
… Except Exception, inst:
… print type(inst) # the exception instance… print inst.args #. Args arguments are stored in the output can … print inst #__str__ arguments directly … x,y=inst # __getitem__ argument can be unpacked directly … print ‘x=’,x
… Print ‘y=’,y
…
(’spam’, ‘eggs’)
(’spam’,'eggs’)
x-spam
y-eggs
If an unhandled exception, an exception is if you have an argument, the end of the message (from the detailed description ` ‘) is output to the part.
Exception handler, try not only to handle exceptions that occur directly in the section, try to handle exceptions that occur inside the function called from a section (which is known even indirectly). ???: For example:
>>> def this_fails():
… x = 1/0
…
>>> try:
… this_fails()
… except ZeroDivisionError, detail:
… print ‘Handling run-time error:’, detail
…
Handling run-time error: integer division or modulo by zero Handling run-time error: integer division or modulo by zero
8.4 throws an exception
raise and use the statement, the programmer will be forced to throw to force a specified exception. For example:
>>> raise NameError, ‘HiThere’
Traceback (most recent call last):
File “”, line 1, in ?
NameError: HiThere
The optional second argument specifies the exception argument. ?????raise NameError(‘HiThere’). The same raise NameError(‘HiThere’) can be written as.
Whether an exception occurs is to determine, and try to handle it if I do not think the simple form you can raise an exception is raised again with the statement:
>>> try:
… raise NameError, ‘HiThere’
… except NameError:
… print ‘An exception flew by!’
… raise
…
An exception flew by! An exception flew by!
Traceback (most recent call last):
File “”, line 2, in ?
NameError: HiThere
Hope this article helped you

Posted in
Tags: 



































