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 except
.
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
try
andexcept
block are executed.- If no exception occurs then code under
except
clause will be skipped.- If file don’t exists then exception will be raised and the rest of the code in the
try
block will be skipped- When exceptions occurs, if the exception type matches exception name after
except
keyword, then the code in thatexcept
clause is executed.
1.2 More exception types
try:
<body>
except <ExceptionType1>:
<handler1>
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>
-
except
acts likeelif
,whentry
through an error,match every exception afterexcept
keyword. If match, then execute; else execute the one without specified exception type. -
else
block is executed only whentry
through no error。 -
finally
will always be executed, with or without exception。
1.3 Example
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
Use 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