python - abnormal program and debug (exception handling)

First, exception handling

For a block of statements at run time may be wrong, you can design a good problem occurs after earlier solutions,

Or the corresponding prompt information. Use try ... except statement to handle exceptions thrown Python:

 

----------------------------------------- # 
# exception catching
# ---- -------------------------------------
# using the pass statement except statement, ignore the exception occurred
list1 = [ '100', ' 200', ' three hundred', 'four hundred', '500']
Total = 0
for E in List1:
the try:
Total = Total + int (E)
the except:
Pass
Print (Total)

# file does not exist
the try:
file = Open ( "config.txt", "r")
the except FileNotFoundError:
( "! file does not exist") Print


# user presses Ctrl + keyboard interrupt exception thrown when the C key combination
pwd = 888 # password
num = -1 # password
times = 0 # wrong passwords are entered
the while NUM = pwd:!
the try:
NUM = int (the iNPUT ( "Please enter the three-digit password: "))
the except ValueError:
print ( "Make sure you enter is the number!")
the Continue
the except: # universal exception caught
print ( "Exit")
BREAK

IF NUM = pwd:!
print ( "! Wrong password")
Times + = 1
IF Times> 3 =:
Print ( "wrong password more than 3 times, please try again tomorrow!")
BREAK
the else:
the Continue
the else:
( "! password is correct") Print
the else:
Print ( "! Login successful")


# uses raise initiative thrown
zero_div DEF ():
the X-100 =
the y-0 =
IF the y-== 0:
# Once an exception is thrown, and did not do the appropriate exception caught, this program will quit.
raise ZeroDivisionError ( "divisor can not be 0!"

Print (z)


# zero_div ()
try:
zero_div ()
the except ZeroDivisionError:
Print ( "to capture a ZeroDivisionError abnormal!")
else: # only try normal circumstances, the statement will be executed else
Print ( "test1")
a finally: # whether it is normal or abnormal will execute the statement
Print ( "test2")

# If you throw a SystemExit exception will force the end of the run Python interpreter
raise SystemExit


----------------------------------------- # 
# custom exception
# --- --------------------------------------
class ExitLoop (Exception):
Pass


the try:
X =. 1
X the while <. 5:
for Y in Range (. 1,. 5):
Print (X, Y)

IF (X ==. 3) and (Y ==. 3):
# by throwing an exception, directly out nested loop
The raise ExitLoop

X + =. 1
the except ExitLoop:
Print ( ". 3, Y =. 3 from bounce when x = nested loop")


class the CustomError (Exception):
DEF the __init __ (self, ERR = 'custom error'):
Exception .__ init__ (Self, ERR)


The raise CustomError

 

Guess you like

Origin www.cnblogs.com/Teachertao/p/11223235.html