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.
RuntimeError | Raised when a generated error does not fall into any category. |
ArithmeticError | Base class for all errors that occur for numeric calculation. |
OverflowError | Raised when a calculation exceeds maximum limit for a numeric type. |
FloatingPointError | Raised when a floating point calculation fails. |
ZeroDivisionError | Raised when division or modulo by zero takes place for all numeric types. |
No comments:
Post a Comment