Exception
Handle Exception
try:
clause
except ExceptI, errorInfo:
if ExceptI is raised, execute this block
except ExceptII, errorInfo:
if ExceptII is raised, execute this block
else:
if no exception, execute this block
finally:
this would always be executed
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, 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, 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, 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, err:
print err.args, err;
Reference