7, Exception handling

1. Declare exception syntax rules

  • Try finally statement

try:
    Detection range
except Exception[as reason]:
    An exception occurred( Exception)Post processing code
finally:
    Code that will be executed anyway

A try statement can be matched with multiple except statements, because there may be multiple types of exceptions in the try statement block. Multiple except statements can be used to capture and handle the exceptions we are interested in respectively.

except (OSError, TypeError, ValueError) as reason:
  print('Error \n The reason for the error is:' + str(reason))
  • raise statement

Used to declare an exception

>>> raise ZeroDivisionError('Exception with divisor zero')
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    raise ZeroDivisionError('Exception with divisor zero')
ZeroDivisionError: Exception with divisor zero

Example: try a new function int_input(), when the user inputs an integer, it returns normally. Otherwise, an error will be prompted and re input is required

def int_input(prompt=''):
	while True:
		try:
			int(input(prompt))
			break
		except ValueError:
			print('Error, the number you entered is not an integer!')

int_input("Please enter an integer:")

2. Use of else statement and with statement

  • else statement

  • Usage 1:
if a>b:
    print(a)
else:
    print(b)
  • Usage 2:
#******************************************#
#  Judge the maximum common divisor of a given number. If it is a prime number, print it  #
#******************************************#
def showMaxFactor(num):
	count = num//2
	while count > 1:
		if num % count == 0:
			print('%d The largest divisor is%d' %(num,count))
			break
		count -= 1
	else:
	# Only after the loop is completed can it be executed. If break is used for execution in the loop, else will not be executed
		print('%d It's prime!' %num)

num = int(input('Please enter a number:'))
showMaxFactor(num)
  • Usage III
try:
	print(int('abc'))
except ValueError as reason:
	print('Something went wrong:' + reason)
else:
	# If there is no error
	print('No exceptions!')
  • with statement

with context_expression [as target(s)]:
    with-body
#**********************************#
#   Exception handling cooperation with sentence     	   #
#	It can avoid the situation that the opened file is not closed    #
#**********************************#
try:
	with open('data.txt', 'w') as f:
		for each_line in f:
			print(each_line)
except OSError as reason:
	print('Something went wrong:' + str(reason))

 

3.Python standard exception summary

Exception nameexplain
AssertionError

Assert statement failure: when the condition behind the assert keyword is false, the program will throw this exception, which is generally used to put a checkpoint in the code

>>> my_list = ['hello world']

>>>Assert len (my_list) > 0 # at this time, the program has no response

>>> my_list.pop()

>>>Assert len (my_list) > 0 # at this time, an exception AssertionError is thrown

AttributeError

Attempt to access an unknown object property: an exception thrown when the object property you are trying to access does not exist

>>> my_list.fishc

Throw an exception: AttributeError: 'list' object has no attribute 'fishc'

EOFErrorThis error basically means that it found an unexpected end of the file. (Ctrl+d on UNIX and Ctrl+Z+Enter on Windows)
FloatingPointErrorFloating point calculation error
GeneratorExitGengeator. When the close () method is called
ImportErrorWhen the import module fails
IndexErrorIndex is out of range for the sequence
KeyErrorFind a keyword that does not exist in the dictionary
KeyboardErrorUser input interrupt key (Ctrl+c)
MemoryErrorMemory overflow (memory can be released by deleting objects)
NameErrorAn attempt was made to access a variable that does not exist
NotImplementedErrorMethods not yet implemented
OSErrorAn exception generated by the operating system (for example, opening a file that does not exist)
OverflowErrorNumeric operation exceeds maximum limit
ReferenceErrorA weak reference attempts to access an object that has been garbage collected
RuntimeErrorGeneral runtime error
StopIterationThe iterator has no more values
SyntaxErrorPython syntax error
IndentationErrorIndent error
TabErrorMixed use of Tab and space
SystemErrorPython compiler system error
SystenExitThe Python compiler process was shut down
TypeErrorInvalid operation between different types
UnboundLocalErrorAccess an uninitialized local variable (subclass of NameError)
UnicodeErrorUnicode related error (subclass of ValueError)
UnicodeEncodeErrorError in Unicode encoding (subclass of Unicode error)
UnicodeDecodeErrorError in Unicode decoding (subclass of Unicode error)
UnicodeTranslateErrorError during Unicode conversion (subclass of Unicode error)
ValueErrorInvalid parameter passed in
ZeroDivisionErrorDivide by zero



 

Keywords: Python

Added by DrDankWD on Thu, 03 Feb 2022 00:22:07 +0200