Exception
Handle Exception
try:
clause
except ExceptI as errorInfo:
if ExceptI is raised, execute this block
except ExceptII as errorInfo:
if ExceptII is raised, execute this block
except:
handle any other exception
else:
if no exception, execute this block
finally:
this would always be executed
#!/usr/bin/python
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError as argument:
print ("Error: can\'t find file or read data", argument)
else:
print ("Written content in the file successfully")
fh.close()
finally:
print("End of try ... except ...")
#!/usr/bin/python
try:
fh = open("testfile", "r")
raise ValueError('Value Error')
except IOError as argument:
print ("Error: can\'t find file or read data\n", argument)
except Exception as err: # handle any exceptions
print(err)
#except: # handle any exceptions
#print ("Error: value error\n")
else:
print ("Written content in the file successfully")
fh.close()
finally:
print("End of try ... except ...")
Raise Exception
raise Exception(errorInfo)
Python Exception Hierarchy
Raise and Handle
#!/usr/bin/python
def div(a, b):
if b == 0:
raise ZeroDivisionError("Denominator is zero ...");
return a/b;
if __name__ == '__main__':
try:
div(1, 0);
except Exception as err:
print(err.args, err);
#!/usr/bin/python
def div(a, b):
assert b != 0, 'AssertionError: Divided by zero ...';
return a/b;
def main():
try:
div(1, 0);
except Exception as err:
print('Catch error in main ...')
raise # relay exception
if __name__ == '__main__':
try:
main()
except Exception as err:
print(err.args, err);
assert
If the expression is false, Python raises an AssertionError exception
#!/usr/bin/python
def div(a, b):
assert b != 0, 'AssertionError: Divided by zero ...';
return a/b;
if __name__ == '__main__':
try:
div(1, 0);
except Exception as err:
print(err.args, err);
python -O Exception.py, turn off assertion
# Exception.py
#!/usr/bin/python
def getString():
return "Hello World!"
if __name__ == '__main__':
s = getString();
assert s == "Hello", "string is not correct ..."
print(s) # Hello World!
Traceback
#!/usr/bin/python
import traceback
if __name__ == '__main__':
try:
div(1, 0);
except Exception as err:
print(err.args, err)
traceback.print_exc();
User-Defined Exceptions
#!/usr/bin/python
class definedExcept(Exception):
def __int__(self, arg):
self.args = arg;
def div(a, b):
if b == 0:
raise definedExcept("Defined Exception ...");
return a/b;
if __name__ == '__main__':
try:
div(1, 0);
except Exception as err:
print(err.args, err);
Reference