1. Catch Exception
1.1 Basic Grammar
Put the code that may cause exception into the block after
try, and then catch it with
except block, if the exception type match, the execute the code block inside
try: # write some code # that might throw exception except <ExceptionType>: # Exception handler, alert the user
For example, reading a file that does not exist will cause
IOError, we can plan ahead for this error.
try: f = open('nofile.txt', 'r') print f.read() f.close() except IOError: print 'file not found'
file not found
The flow is as listed：
- First statement between
exceptblock are executed.
- If no exception occurs then code under
exceptclause will be skipped.
- If file don’t exists then exception will be raised and the rest of the code in the
tryblock will be skipped
- When exceptions occurs, if the exception type matches exception name after
exceptkeyword, then the code in that
exceptclause is executed.
1.2 More exception types
try: <body> except <ExceptionType1>: <handler1> except <ExceptionTypeN>: <handlerN> except: <handlerExcept> else: <process_else> finally: <process_finally>
trythrough an error，match every exception after
exceptkeyword. If match, then execute; else execute the one without specified exception type.
elseblock is executed only when
trythrough no error。
finallywill always be executed, with or without exception。
num1, num2 = 1,0 try: result = num1 / num2 print("Result is", result) except ZeroDivisionError: print("Division by zero is error !!") except: print("Wrong input") else: print("No exceptions") finally: print("This will execute no matter what you input")
Division by zero is error !! This will execute no matter what you input
2. Throw erroe
raise to throw self defined exception。
raise ExceptionClass('Your argument')
def enterage(age): if age < 0: raise ValueError("Only positive integers are allowed") if age % 2 == 0: print("age is even") try: num = int(input("Enter your age: ")) enterage(num) except ValueError: print 'Only positive integers are allowd' except: print 'Something went wrong'
Enter your age: -3 Only positive integers are allowd
More information onDocuments。
3. Manipulate exception
We can pass the exception to a variable, and it’s pretty easy.
try: # this code is expected to throw exception except ExceptionType as ex: # code to handle exception
try: number = int(input("Enter a number: ")) print "The number entered is", number except NameError as ex: print "Exception:", ex
Enter a number: one Exception: name 'one' is not defined