Errors
A syntax error is an error in the python program.
Example:
>>> while True print 'Hello world'
it is an Invalid Syntax error in the above code. It should be as :
>>> while True: print 'Hello world'
Standard Errors available in Python are:
IndentationError, SystemExit, ValueError, TypeError, RuntimeError
Exceptions
Errors detected during execution are called exceptions. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.
Example:
>> 10 * (1/10)
The above code is syntactically right, but when we execute it, but it will produce ZeroDivisionError: integer division or modulo by zero.
Standard Exceptions available in Python are:
FloatingPointError, ZeroDivisonError, EOFError, SystemExit, OverflowError, KeyboardInterrupt, IndexError, IOError
Handling an Exception
If we see some doubtful code that may produce an exception, we can secure our program by placing the code inside the try-except block.
Syntax:
try: you do your operation here except Exception1: if there is Exception1, then execute this block except Exception2: if there is Exception2, then execute this block ......... else: if there is no exception error, then execute this block of code.
try: fh = open("testfile", "r") 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")