Wednesday 10 May 2017

Python2

The assert Statement

#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
   assert (Temperature >= 0),"Colder than absolute zero!"
   return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print KelvinToFahrenheit(-5)
32.0

Traceback (most recent call last):
File "test.py", line 9, in 
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!  

 

Handling an exception

try:
   You do your operations here;
   ......................
except ExceptionI:
   If there is ExceptionI, then execute this block.
except ExceptionII:
   If there is ExceptionII, then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

 

#!/usr/bin/python

try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find file or read data"
else:
   print "Written content in the file successfully"
   fh.close()
You can also use the except statement with no exceptions defined as follows −
try: 
 You do your operations here; 
 ...................... 
 except: 
        If there is any exception, then execute this block.  
         ......................  
  else: 
      If there is no exception then execute this block.

RuntimeErrorRaised when a generated error does not fall into any category.
ArithmeticErrorBase class for all errors that occur for numeric calculation.
OverflowErrorRaised when a calculation exceeds maximum limit for a numeric type.
FloatingPointErrorRaised when a floating point calculation fails.
ZeroDivisionErrorRaised when division or modulo by zero takes place for all numeric types.

 

No comments:

Post a Comment