Exception Handling in Python

This section introduces methods for exception handling in Python.

Common Exceptions

Common exceptions in Python are listed in Table 12-1. Python assigns names to different types of errors. During programming, if an error occurs, it can be caught and checked whether it is a specified type of error, and corresponding handling can be performed.

Table 12-1 Common Exceptions in Python

Continued Table

Exception Handling: Single-Branch Case

In Python, the try...except...else...finally... structure is used to catch exceptions. Depending on needs, simple single-branch forms or multi-branch forms with else and finally can be used.

Below, the single-branch case is introduced. There are two syntax formats for single-branch exception handling.

The first format is as follows:

code.python
try:
    <statement>
except:
    print('Exception description')
The second format is class="text-secondary">as follows:
python
try:
    <statement>
except <ExceptionName>:
    print('Exception description')

The first format catches all errors, and the second format catches specified errors. Here, the try block executes the specified code normally, and the except block catches errors and performs related display and handling. Generally, avoid using the first format or handle unknown errors in multi-branch cases.

In the following code, the try block attempts to use a variable that is not declared or assigned. The except block catches the NameError type error and outputs it.

code.python
>>> try:
    f
except NameError class="text-secondary">as e:
    print(e)

Press Enter. Since an undeclared variable is used, the error "name 'f' is not defined" is caught, and the output is as follows:

code.python
name 'f' is not defined

Exception Handling: Multi-Branch Case

If the caught error may belong to multiple types, use the multi-branch form for handling. The syntax format for multi-branch exception handling is as follows:

code.python
try:
    <statement>
except(<ExceptionName1>, <ExceptionName2>, ...):
    print('Exception description')

The following code performs division. If an error occurs, it catches the "division by zero" error and the "variable not defined" error. The except statement specifies these two error names using a tuple and outputs the caught error result.

code.python
>>> b = 0
>>> try:
    3 / b
except(ZeroDivisionError, NameError) class="text-secondary">as e:
    print(e)

Press Enter. The caught error is as follows:

code.python
division by zero

Multi-branch error handling can also be written in the following form, judging in sequence:

code.python
try:
    <statement>
except <ExceptionName1>:
    print('Exception description 1')
except <ExceptionName2>:
    print('Exception description 2')
except <ExceptionName3>:
    print('Exception description 3')

Rewrite the above example code as follows:

code.python
>>> try:
    3 / 0
except ZeroDivisionError class="text-secondary">as e:
    print(e)
except NameError class="text-secondary">as e:
    print(e)

Press Enter to get the same output result:

code.python
division by zero

Exception Handling: try…except…else…

Single-branch and multi-branch forms are used to catch and handle errors. How to handle cases where no error is caught? This uses the try…except…else… structure introduced in this section, as shown below. Here, the else block handles cases where no exception is found.

code.python
try:
    <statement>
except <ExceptionName1>:
    print('Exception description 1')
except <ExceptionName2>:
    print('Exception description 2')
else:
    <statement>

The following code calculates 3/2. If no error is caught, it outputs a series of equal signs.

code.python
>>> b = 2
>>> try:
    3 / b
except(ZeroDivisionError, NameError) class="text-secondary">as e:
    print(e)
else:
    print('==========')

Press Enter. The calculation result is 1.5, no error is caught, so a series of equal signs is output:

code.python
1.5
==========

Exception Handling: try…finally…

The try...finally... structure executes the code in the finally block regardless of whether an exception occurs. Its syntax format is as follows:

code.python
try:
    <statement>
finally:
    <statement>

In the following example code, 3/0 is calculated. Since the divisor is 0, the except block catches the "division by zero" error and outputs the error information. However, even if an error occurs, the code in the finally block is executed for handling.

code.python
>>> try:
    3 / 0
except ZeroDivisionError class="text-secondary">as e:
    print(e)
finally:
    print('Execute finally')

Press Enter. The output is as follows. The first line is the "division by zero" error information, and the second line is the output result of the finally block.

code.python
division by zero
Execute finally
Language Variable Name Reason for Invalidity
Excel VBA 123Tree Does not start with a letter
Excel VBA _Tree Does not start with a letter
Excel VBA Tree#?green Contains characters other than letters, numbers, and underscores
Excel VBA Then Variable name is an Excel VBA keyword
Python 123tree Starts with a number
Python Tall Tree Contains spaces
Python Tree?12# Contains characters other than letters, numbers, and underscores
Python for Variable name is a Python keyword
Data Type Name Variable Naming Prefix Storage Size Description VarType Return Value
Boolean Boolean bln 2 bytes 16-bit, value is True or False 11
Byte Character byt 1 byte 8-bit unsigned integer 17
Integer Short Integer int 2 bytes 16-bit integer 2
Long Long Integer lng 4 bytes 32-bit integer
Single Single-Precision Float sng 4 bytes 32-bit real number 4
Double Double-Precision Float dbl 8 bytes 64-bit real number 5
String String str String size String value 8
String*n Fixed-Length String Fixed-length string value
Currency Currency cur 8 bytes 64-bit fixed-point real number 6
Date Date dat 8 bytes 64-bit real number (date/time) 7
Variant Variant var Variable Can represent any of the above types 12
User Type Custom Type Custom type defined by Type 36
Object Object obj 4 bytes 32-bit object reference 9
Type Name Type Character Description Example
Boolean bool Value is True or False >>> a = True; b = False
Integer int Represents integers, no size limit (can represent very large numbers) >>> a = 1; b = 10000000
Float float Decimal numbers, can be in scientific notation >>> a = 1.2; b = 1.2e3
String str Character sequence, elements are immutable >>> a = 'A'; b = 'A'
List list Elements can be different types, ordered, mutable, and repeatable >>> a = [1, 'A', 3.14, []]
Tuple tuple Similar to list, elements are immutable >>> a = (1, 'A', 3.14, ())
Dictionary dict Unordered collection of key-value pairs, mutable, keys are unique >>> a = {1: 'A', 2: 'B'}
Set set Unordered, mutable, and non-repeating elements >>> a = {1, 3.14, 'name'}
None NoneType Represents an empty object >>> a = None
Function Syntax Functionality Parameters
CBool CBool(Num $) Converts to Boolean: 0 → False, others → True
CByte CByte(Num $) Converts to Byte
CCur CCur(Num $) Converts to Currency
CDate CDate(Num $) or CVDate(Num $)
CDbl CDbl(Num $) Converts to double-precision float
CInt CInt(Num $) Converts to 16-bit short integer (overflow error if too large/small)
CLng CLng(Num $) Converts to 32-bit long integer (overflow error if too large/small)
CSng CSng(Num $) Converts to single-precision float (overflow error if too large/small)
CStr CStr(Num $) Converts to string
CVar CVar(Num $) Converts to Variant
Val Val(S$) Returns the numeric value of S$ S$: String to return the numeric value (octal if starts with &O, hex if &H)
Function Description
int(x [,base]) Converts object x to integer
float(x) Converts object x to float
complex(real [,imag]) Creates a complex number
str(x) Converts object x to string
repr(x) Converts object x to an expression string
eval(str) Evaluates a valid Python expression in string str and returns an object
tuple(s) Converts sequence s to a tuple
list(s) Converts sequence s to a list
set(s) Converts sequence s to a mutable set
dict(d) Creates a dictionary(d must be a sequence of(key, value) tuples)
Operator Description Expression
+ Add two variables a + b
- Negate a variable or subtract two variables -a or a - b
* Multiply two variables a * b
/ Divide two variables a / b
\ Integer division a \ b
Mod Modulo operation (remainder of division) a Mod b
^ Exponentiation a ^ b
Operator Description Expression
+ Add two variables a + b
- Negate a variable or subtract two variables -a or a - b
* Multiply two variables or repeat sequences (e.g., strings) a * b
/ Divide two variables a / b
// Integer division (floor division). For positive results, returns the integer part of the quotient; for negative results, returns the truncated value minus 1. If at least one variable is a float, returns a float. a // b
% Modulo operation (remainder of division) a % b
** Exponentiation a ** b
Operator Description Expression
= Equal to a = b
<> Not equal to a <> b
< Less than a < b
> Greater than a > b
<= Less than or equal to a <= b
>= Greater than or equal to a >= b
Operator Description Expression
== Equal to a == b
!= Not equal to a != b
< Less than a < b
Operator Description Expression
> Greater than a > b
<= Less than or equal to a <= b
>= Greater than or equal to a >= b
Operator Description Expression
Not Negation. True becomes False, and vice versa. Not a
And Conjunction. Returns True only if both operands are True; otherwise False. a And b
Or Disjunction. Returns True if at least one operand is True; returns False only if both are False. a Or b
Xor Exclusive OR. Returns False if both operands are the same (both True or both False); otherwise True. a Xor b
Operator Description Expression
Eqv Equivalence. Returns True if both operands are the same (both True or both False); otherwise False. a Eqv b
Imp Implication. Returns False only if the left operand is True and the right operand is False; otherwise True. a Imp b
Operator Description Expression
not Negation. True becomes False, and vice versa. not a
and Conjunction. Returns True only if both operands are True; otherwise False. a and b
or Disjunction. Returns True if at least one operand is True; returns False only if both are False. a or b
^ Exclusive OR. Returns False if both operands are the same (both True or both False); otherwise True. a ^ b
Operator Description
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulo assignment
**= Exponentiation assignment
//= Integer division assignment
Operator Description
in Returns True if the value is in the sequence; otherwise False.
not in Returns True if the value is not in the sequence; otherwise False.
Operator Description Precedence
( ) Parentheses 16 (highest)
x(i) Indexing 15
^ Exponentiation 14
~ Bitwise NOT 13
+/- Unary plus/minus 12
*, / Multiplication/division 11
\ Integer division 10
Mod Modulo 9
+, - Addition/subtraction 8
& String concatenation 7
=, <>, >, >=, <, <=, Like, New, TypeOf, Is, IsNot Comparison/identity 6
Not Logical NOT 5
And Logical AND 4
Or Logical OR 3
Xor Exclusive OR 2
Eqv Equivalence 1 (lowest)
Operator Description Precedence
( ) Parentheses 18 (highest)
x[i] Indexing 17
x.attribute Attribute/method access 16
** Exponentiation 15
~ Bitwise NOT 14
+/- Unary plus/minus 13
*, /, //, % Multiplication/division/modulo 12
Operator Description Precedence
+, - Addition/subtraction 11
>>, << Bitwise shift 10
& Bitwise AND 9
^ Bitwise XOR 8
` ` Bitwise OR
==, !=, >, >=, <, <= Comparison 6
is, is not Identity 5
in, not in Membership 4
not Logical NOT 3
and Logical AND 2
or Logical OR 1 (lowest)
Python Package Description
xlrd Supports reading .xls and .xlsx files
xlwt Supports writing .xls files
OpenPyXL Supports reading/writing .xlsx, .xlsm, .xltx, and .xltm files; supports the Excel object model and does not depend on Excel
xlsxWriter Supports writing .xlsx files and VBA
win32com Encapsulates all Excel objects used by VBA
comtypes Encapsulates all Excel objects used by VBA
xlwings Re-encapsulates the win32com package; supports mixed programming with VBA and data type conversion with various data types
pandas Supports reading/writing .xls and .xlsx files; provides various functions for data processing, making processing simpler and faster
Escape Char Meaning Escape Char Meaning
\n Newline \b Backspace
\t Tab \000 Null
\ Escapes itself \v Vertical tab
' Single quote \r Carriage return
" Double quote \f Form feed
Char Chr Function Constant
Carriage return Chr(13) vbCr
Line feed Chr(10) vbLf
CRLF Chr(13)+Chr(10) vbCrLf
Tab Chr(9) vbTab
Slice Operation Meaning Example Result
[: ] Whole string 'abcde'[ : ] 'abcde'
[start: ] From start to end 'abcde'[2: ] 'cde'
[:end] From beginning to end-1 'abcde'[:2] 'ab'
[start:end] From start to end-1 'abcde'[2:4] 'cd'
[start:end:step] From start to end-1, step size step 'abcde'[1:4:2] 'bd'
[-n: ] Last n chars 'abcde'[-3:] 'cde'
[-m:-n] From -m to -n-1 'abcde'[-4:-2] 'bc'
[: -n] From beginning to -n-1 'abcde'[:-1] 'abcd'
[:: -s] Reverse with step s 'abcde'[::-1] 'edcba'
Format Description
General Number Plain number; removes thousand separators and trailing zeros.
Currency Currency type; adds thousand separators and currency symbol; 2 decimal places.
Fixed Number with 2 decimal places.
Standard Thousand separators and 2 decimal places.
Percent Percentage with 2 decimal places.
Scientific Scientific notation.
Yes/No Returns "Yes" if non-zero; otherwise "No".
True/False Returns "True" if non-zero; otherwise "False".
"" or omitted Returns original string, removing leading/trailing zeros around decimal.
0 Placeholder; pads with zeros if insufficient length.
# Placeholder; does not pad if insufficient length.
% Converts to percentage (multiplies by 100).
\ Forces display of a character.
; Separates segments for different formats.
General Date Basic date/time (e.g., 2021/5/23 11:05:12).
Long Date OS-defined long date (e.g., 2021年5月23日).
Medium Date OS-defined medium date (e.g., 21-05-23).
Short Date OS-defined short date (e.g., 2021-5-23).
Long Time OS-defined long time (e.g., 11:05:12).
Medium Time 12-hour format with AM/PM, no seconds (e.g., 11:05 AM).
Short Time 24-hour format, no seconds (e.g., 11:05).
c National standard date/time (e.g., 2021/5/23 11:05:12).
y Day of year (1–366, e.g., 100).
yy 2-digit year (00–99, e.g., 21).
yyy Combines yy and y (e.g., 21100).
yyyy 4-digit year (0100–9999, e.g., 2021).
d Day of month (1–31, e.g., 2).
dd Same as d, but pads with zero if <10 (e.g., 02).
ddd 3-letter weekday (e.g., "Sat").
dddd Full weekday name (e.g., "Saturday").
ddddd Standard date (e.g., 2021/5/23).
dddddd Long date (e.g., 2021年5月23日).
w Day of week (Sunday=1, e.g., 6).
ww Week of year (e.g., 12).
m Month (or minutes if used in time, e.g., 5).
mm Month with leading zero if <10 (or minutes, e.g., 05).
mmm 3-letter month (e.g., "May").
mmmm Full month name (e.g., "May").
h, hh Hour (0–23, e.g., 3, 03).
n, nn Minute (0–59, e.g., 9, 09).
s, ss Second (0–59, e.g., 5, 05).
Placeholder Description
%c Character and ASCII code.
%s String.
%d Integer.
%o Octal number.
%x Hexadecimal (lowercase).
%X Hexadecimal (uppercase).
%f Floating-point (specify precision).
%e Scientific notation (lowercase exponent).
%E Scientific notation (uppercase exponent).
%g Auto-selects %f or %e.
%G Auto-selects %f or %E.
%p Variable address in hexadecimal.
Function Description
operator.lt(str1, str2) Returns True if str1 < str2.
operator.le(str1, str2) Returns True if str1 <= str2.
operator.eq(str1, str2) Returns True if str1 == str2.
operator.ne(str1, str2) Returns True if str1 != str2.
operator.gt(str1, str2) Returns True if str1 > str2.
operator.ge(str1, str2) Returns True if str1 >= str2.
Function Description
str.isalnum() True if all characters are alphanumeric.
str.isalpha() True if all characters are alphabetic.
str.isdigit() True if all characters are digits.
str.isnumeric() True if all characters are numeric.
str.islower() True if all letters are lowercase.
str.isupper() True if all letters are uppercase.
str.isspace() True if all characters are whitespace.
max(str) Largest character (by ASCII value).
min(str) Smallest character (by ASCII value).
Function Description
Count Number of numeric elements
CountA Total number of elements (numbers, strings, etc.)
Max Maximum value
Min Minimum value
Large Nth largest value
Small Nth smallest value
Sum Sum of elements
Average Mean of elements
Mode Mode (most frequent value)
Median Median value
Function Description
Abs Returns the absolute value
Exp Returns the power value with base e
Sqr Returns the square root (parameter ≥ 0)
Log Returns the natural logarithm (parameter > 0)
Function Description
Sgn Returns the sign of the parameter: 1 if > 0, 0 if = 0, -1 if < 0
Sin Returns the sine value
Cos Returns the cosine value
Tan Returns the tangent value
Atn Returns the arctangent value
Function Description
Date Returns the system date
Time Returns the system time
Year Returns the current year of the system
Month Returns the current month of the system
Day Returns the current day of the system
Weekday Returns the current weekday of the system
Hour Returns the hour of the system (0–23)
Minute Returns the minute of the system (0–59)
Second Returns the second of the system (0–59)
Function Description Function Description
abs Returns the absolute value round Rounds a floating-point number
eval Evaluates a given expression sum Calculates the sum
max Returns the maximum value sorted Sorts
min Returns the minimum value filter Filters
pow Power operation
Function Description Function Description
math.ceil(x) Returns the smallest integer greater than or equal to x math.sqrt(x) Returns the square root of x
math.fabs(x) Returns the absolute value of x math.sin(x) Returns the sine value of x
math.floor(x) Returns the largest integer less than or equal to x math.cos(x) Returns the cosine value of x
math.fsum(iter) Returns the sum of elements in an iterable object math.tan(x) Returns the tangent value of x
math.gcd(*ints) Returns the greatest common divisor of given integer arguments math.atan(x) Returns the arctangent value of x
math.isfinite(x) Returns True if x is not infinity or NaN, otherwise False math.asin(x) Returns the arcsine value of x
math.isinf(x) Returns True if x is infinity, otherwise False math.acos(x) Returns the arccosine value of x
math.isnan(x) Returns True if x is NaN, otherwise False math.sinh(x) Returns the hyperbolic sine value of x
math.isqrt(n) Returns the integer square root of n (square root rounded down), n ≥ 0 math.cosh(x) Returns the hyperbolic cosine value of x
math.lcm(*ints) Returns the least common multiple of given integer arguments math.tanh(x) Returns the hyperbolic tangent value of x
math.trunc(x) Returns the truncated integer of x math.asinh(x) Returns the inverse hyperbolic sine value of x
math.exp(x) Returns e raised to the power of x math.acosh(x) Returns the inverse hyperbolic cosine value of x
math.log(x[, base]) Returns the natural logarithm of x math.atanh(x) Returns the inverse hyperbolic tangent value of x
math.log2(x) Returns the base-2 logarithm of x math.dist(p, q) Returns the distance between points p and q
math.log10(x) Returns the base-10 logarithm of x math.degrees(x) Converts x class="text-secondary">from radians to degrees
math.pow(x, y) Returns x raised to the power of y math.radians(x) Converts x class="text-secondary">from degrees to radians
Exception Description
ArithmeticError Errors caused by arithmetic operations
FloatingPointError Errors caused by floating-point calculations
OverflowError Overflow errors caused by excessively large calculation results
ZeroDivisionError Division by zero
AttributeError Errors caused by failed attribute reference or assignment
BufferError Errors caused when buffer-related operations cannot be performed
ImportError Errors caused by failing to class="text-secondary">import a module/object
ModuleNotFoundError No module found or None found in sys.modules
IndexError Errors caused by the absence of an index in a sequence
KeyError Errors caused by the absence of a key in a mapping
Exception Description
MemoryError Memory overflow error
NameError Errors caused by an undeclared or uninitialized object
UnboundLocalError Errors caused by accessing an uninitialized local variable
OSError Operating system errors
FileExistsError Errors caused by creating an existing file or directory
FileNotFoundError Errors caused by using a non-existent file or directory
InterruptedError Errors caused by a system call being interrupted by an input signal
IsADirectoryError Errors caused by requesting file operations on a directory
NotADirectoryError Errors caused by requesting directory operations on a non-directory object
TimeoutError System-level timeout of system functions
RuntimeError Runtime errors
SyntaxError Syntax errors
SystemError Internal errors found by the interpreter
TypeError Object type errors