A programmer-defined exception class. : Exception Class « Exception « Python






A programmer-defined exception class.

A programmer-defined exception class.
import math

class NegativeNumberError( ArithmeticError ):
   pass

def squareRoot( number ):
   if number < 0:
      raise NegativeNumberError, "Square root of negative number not permitted"
   return math.sqrt( number )

while 1:
   try:
      userValue = float( raw_input( "\nPlease enter a number: " ) )
      print squareRoot( userValue )
   # float raises ValueError if input is not numerical
   except ValueError:
      print "The entered value is not a number"
   # squareRoot raises NegativeNumberError if number is negative
   except NegativeNumberError, exception:
      print exception
   else:
      break

           
       








Related examples in the same category

1.User-defined Exceptions: Name their own exceptions by creating a new exception classUser-defined Exceptions: Name their own exceptions by creating a new exception class
2.Create a base class for exceptions defined by a module