Raising Exceptions - Python

Raising the SystemExitexception is a generic way to leave the Python interpreter.

C:\Program Files\Python>python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 StichtingMathematisch Centrum, Amsterdam
>>> raise SystemExit
C:\Program Files\Python>

The next example demonstrates how you can trap the SystemExitexception.

>>> try:
… raiseSystemExit
… exceptSystemExit:
… print "Sorry. You can not leave."

Sorry. You can not leave.

The sys.exit() function raises an exception SystemExitthat, if not caught, causes the thread to exit silently.

>>> import sys
>>> try:
… sys.exit()
… exceptSystemExit:
… print "I have already told you. You can not leave."

I have already told you. You can not leave.

Raising an Exception to Leave Nested Loops

Sometimes you are so deeply involved in your data structures that you only want to get out of all your nested loops quickly. Normally, you would have to use break for each level of interaction. The next example demonstrates how to handle this situation by using exceptions.

>>>ExitLoop = "ExitLoop"
>>> try:
… i=1
… while i < 10:
… for j in xrange(1,5):
… printi,j
… if (i==2) and (j==3):
… raiseExitLoop
… i = i + 1
… exceptExitLoop:
… print "i=2 and j=3 is a special case."

1 1
1 2
1 3
1 4
2 1
2 2
2 3
i=2 and j=3 is a special case.

Raising String Exceptions

Older versions used to support only strings for both Python standard exceptions and user-defined exceptions.

>>>NetworkError = "NetworkError"
>>> raise NetworkError, "Bad hostname"

Nowadays, Python supports both strings and exception classes. There are costs to using class exceptions because they must be instantiated to be caught. Note that most people don't use exceptions to control the flow of their program, so they don't occur much.

However, classes give you much more flexibility to generalize the type of error that you want to catch.

Instancing an Exception Class

Every time an exception is raised, an instance of the exception class is created. The next syntax demonstrates how to catch a class instance in your program.

try:
<statements>
except exception, instance:
<statements>

The instance variable is an instance of the raised exception. Therefore, it inherits attributes from the exception class.

Each instance has an attribute called argsthat returns the error string in a tuple format.

>>> try:
… a = [1,2]
… print a[4]
… exceptIndexError, b:
… printb.args

('list index out of range',)

Particularly, the EnvironmentErrorexception has a 2-tuple or 3-tuple structure that can be translated as (error number, string error message, and an optional filename).

>>> try:
… file = open("Parrot")
… exceptEnvironmentError, b:
… printb.args

(2, 'No such file or directory')

When the instance belongs to a SyntaxErrorclass exception, four special attributes are also returned: filename, lineno, offset, and text.

>>> try:
… a = "x===10"
… exec a
… exceptSyntaxError, b:
… printb.args

('invalid syntax', (None, 1, 4, 'x===10'))

Debugging Your Code

Exceptions are very good for helping to debug your code. You can use the assert command to raise a debugging exception that transports a message to your exception handling code.

The syntax is assert <TestStatement> [,argument] This command raises an Assertion Error exception whenever <Test Statement>evaluates to false. For example

>>>def divide (a,b):
… assert b != 0, "Can't divide by zero"
… return a/b
>>>
>>>divide(10,0)
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in divide
AssertionError: Can't divide by zero
The assert command is equivalent to
>>>if __debug__:c
>>>if not (<TestStatement>):
>>> raise AssertionError [, argument]

__debug__ is a built-in name and has its value set to true by default. To set __debug__ to false, it is necessary to change the interpreter to run in optimized mode.

c:\>python -O

Currently, Python's command-line option -X turns all standard exceptions into strings. Version 1.6 is expected to have this option removed, and make all standard exceptions into classes. User code that deals with string exceptions will still be supported, but not encouraged.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Python Topics