8th Chapter Anomalies
8.1 What is an exception
>>> 1/0
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
1/0
Zerodivisionerror:integer division or modulo by zero
8.2 Error in your own way
8.2.1 Raise statement
>>> Raise Exception
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
Raise Exception
Exception
>>> Raise Exception (' hyperdrive overload ')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
Raise Exception (' hyperdrive overload ')
Exception:hyperdrive overload
>>> Import Exceptions
>>> Dir (Exceptions)
[' Arithmeticerror ', ' assertionerror ', ' attributeerror ', ' baseexception ', ' deprecationwarning ', ' eoferror ', ' EnvironmentError ', ' Exception ', ' floatingpointerror ', ' futurewarning ', ' generatorexit ', ' ioerror ', ' importerror ', ' Importwarning ', ' indentationerror ', ' indexerror ', ' keyerror ', ' keyboardinterrupt ', ' lookuperror ', ' MemoryError ', ' Nameerror ', ' notimplementederror ', ' oserror ', ' overflowerror ', ' pendingdeprecationwarning ', ' referenceerror ', ' RuntimeError ', ' runtimewarning ', ' standarderror ', ' stopiteration ', ' syntaxerror ', ' syntaxwarning ', ' SystemError ', ' Systemexit ', ' taberror ', ' typeerror ', ' unboundlocalerror ', ' unicodedecodeerror ', ' unicodeencodeerror ', ' Unicodeerror ', ' unicodetranslateerror ', ' unicodewarning ', ' userwarning ', ' valueerror ', ' Warning ', ' windowserror ', ' Zerodivisionerror ', ' __doc__ ', ' __name__ ']
>>> Raise Arithmeticerror
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
Raise Arithmeticerror
Arithmeticerror
>>>
8.3 Catching exceptions
>>> Try:
x = input (' Input the x: ')
y = input (' Input the Y: ')
Print x/y
Except Zerodivisionerror:
print ' The second number should not is zero! '
Input the X:10
Input the y:0
The second number should not is zero!
>>> Try:
x = input (' Input the x: ')
y = input (' Input the Y: ')
Print x/y
Except Zerodivisionerror:
print ' The second number should not is zero! '
Input the X:8
Input the Y:9
0
Shielding 0 Errors
>>> class Muffledcalculator:
muffled = False
Def calc (self,expr):
Try
return eval (expr)
Except Zerodivisionerror:
If self.muffled:
print ' division by the zero is illegal '
Else
Raise
>>> calculator = Muffledcalculator ()
>>> calculator.calc (' 10/2 ')
5
>>> calculator.calc (' 10/0 ')
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
Calculator.calc (' 10/0 ')
File "<pyshell#37>", line 5, in Calc
return eval (expr)
File "<string>", line 1, in <module>
Zerodivisionerror:integer division or modulo by zero
>>> calculator.muffled = True
>>> calculator.calc (' 10/0 ')
Division by the zero is illegal
If you catch an exception, but you want to throw it back, that is, to pass an exception, you can call raise with no arguments and explicitly provide specific exceptions when you catch an exception
If this behavior is activated, then the calculator will print the error message, rather than let the exception propagate, if it is in the process of user interaction, then this is useful.
But if used inside the program, it would be better to throw the exception, so the shielding mechanism could be turned off.
8.4 More than one except clause
>>> Try:
x = input (' Input the x: ')
y = input (' Input the Y: ')
Print x/y
Except Zerodivisionerror:
print ' The second number should not is zero! '
Except TypeError:
print ' That is not a number?! '
Input the X:10
Input the y: ' Hi '
That is not a number?!
8.5 Catch two exceptions with a block
>>> Try:
x = input (' Input the x: ')
y = input (' Input the Y: ')
Print x/y
Except (Zerodivisionerror, TypeError, Nameerror):
print ' Your numbers were bogus ... '
Input the X:8
Input the y:0
Your numbers were bogus ....
>>> Try:
x = input (' Input the x: ')
y = input (' Input the Y: ')
Print x/y
Except (Zerodivisionerror, TypeError, Nameerror):
print ' Your numbers were bogus ... '
Input the X:10
Input the y: ' Hi '
Your numbers were bogus ....
8.6 Capturing objects
>>> Try:
x = input (' Input the x: ')
y = input (' Input the Y: ')
Print x/y
Except (Zerodivisionerror, TypeError), E:
Print E
Input the X:10
Input the y:0
Integer division or modulo by zero
>>> E
Zerodivisionerror (' integer division or modulo by Zero ',)
>>> Try:
x = input (' Input the x: ')
y = input (' Input the Y: ')
Print x/y
Except (Zerodivisionerror, TypeError), E:
Print E
Input The x: ' Hello '
Input The y: ' World '
Unsupported operand type (s) for/: ' STR ' and ' str '
>>> E
TypeError ("Unsupported operand type (s) for/: ' STR ' and ' str '",)
8.7 true Total Capture
>>> Try:
x = input (' Input the x: ')
y = input (' Input the Y: ')
Print x/y
Except:
print ' Something was wrong ... '
Input the X:8
Input the y: ' haha '
Something was wrong ...
8.8 Bob
>>> Try:
print ' A simple task. '
Except
print ' What? Something was wrong? '
Else
print ' Ah ... It was as planned '
A simple task.
Ah ... It was as planned
Always enter until legal input
>>> while True:
Try
x = input (' Input the x: ')
y = input (' Input the Y: ')
Value = x/y
print ' x/y is ', value
Except
print ' Invalid input. Please try again '
Else
Break
Input the X:8
Input the y:0
Invalid input. Please try again
Input the X:8
Input the y: ' 1 '
Invalid input. Please try again
Input the X:8
Input The Y:
Invalid input. Please try again
Input the X:9
Input the Y:2
X/y is 4
Printing error messages
>>> while True:
Try
x = input (' Input the x: ')
y = input (' Input the Y: ')
Value = x/y
print ' x/y is ', value
Except Exception, E:
print ' Invlid input ', E
print ' Invalid input. Please try again '
Else
Break
Input the X:1
Input the y:0
Invlid Input Integer division or modulo by zero
Invalid input. Please try again
Input the X:4
Input the y: ' 2 '
Invlid input unsupported operand type (s) for/: ' int ' and ' str '
Invalid input. Please try again
Input the X:3
Input The Y:
Invlid input Unexpected EOF while parsing (<STRING>, line 0)
Invalid input. Please try again
Input the X:4
Input the Y:2
X/y is 2
8.9 last
>>> x = None
>>> Try:
x = 1/0
Finally
print ' Cleaning up ... '
del X
Cleaning up ...
Traceback (most recent call last):
File "<pyshell#6>", line 2, in <module>
x = 1/0
Zerodivisionerror:integer division or modulo by zero
>>>
>>> Try:
1/0
Except Nameerror:
print ' unkown variable '
Else
print ' It is OK. '
Finally
print ' Cleaning up ... '
Cleaning up.
Traceback (most recent call last):
File "<pyshell#17>", line 2, in <module>
1/0
Zerodivisionerror:integer division or modulo by zero
>>>
8.10 Exceptions and functions
def faulty ():
Raise Exception (' Something is wrong. ')
Def ignore_exception ():
Faulty ()
Def Handle_excepton ():
Try
Faulty ()
Except
print ' Exception handled '
print ' ignore_exception () '
Ignore_exception ()
Ignore_exception ()
Traceback (most recent call last):
File "F:/python/8-1 functions and exceptions. py", line one, in <module>
Ignore_exception ()
File "F:/python/8-1 function and exception. Py", line 4, in Ignore_exception
Faulty ()
File "F:/python/8-1 function and exception. Py", line 2, in faulty
Raise Exception (' Something is wrong. ')
Exception:something is wrong.
>>> handle_exception ()
Exception handled
>>>
8.11
>>> def describleperson (person):
print ' Description of ', person[' name '
print ' Age: ', person[' age '
Try
print ' Occupation: ' +person[' occupation ']
Except Keyerror:
Pass
>>> person = {' name ': ' ABC ', ' Age ': 21}
>>> person
{' Age ': ' Name ': ' ABC '}
>>> Describleperson (person)
Description of ABC
Age:21