1. 抛出异常
raise:抛出异常 只能在try代码块中抛出 不能像java让函数抛出异常
def calculate ( i, j) :
if j == 0 :
raise Exception( "Cannot calculate" )
print ( i / j)
try :
calculate( 5 , 0 )
except Exception as e:
print ( str ( e) )
else :
print ( "Finish" )
2. 取得回溯字符串
traceback.format_exc():获取回溯信息
import traceback
try :
raise Exception( "Exception" )
except Exception as e:
print ( traceback. format_exc( ) )
3. 断言
assert 布尔表达式:如果为 False 则回溯报错 AssertionError
nums = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
nums. reverse( )
assert nums[ 0 ] <= nums[ - 1 ]
4. 日志
4.1 使用 logging 模块
logging.basicConfig():日志格式设置 logging.debug():调用logging.basicConfig()以输出信息
import logging
logging. basicConfig(
level= logging. DEBUG,
format = '%(asctime)s - %(levelname)s - %(message)s' )
logging. debug( 'Starting' )
def test ( n) :
logging. debug( f'Starting logging( { n} )' )
total = 1
for i in range ( 1 , n + 1 ) :
total *= i
logging. debug( f"i = { i} ,total = { total} " )
logging. debug( f'Finished logging( { n} )' )
return total
print ( test( 5 ) )
logging. debug( 'Finished' )
4.2 日志级别
级别 日志函数 描述 DEBUG logging.debug() 小细节 INFO logging.info() 记录程序中的一般事件的信息 WARNING logging.warning() 表示可能的问题 ERROR logging.error() 记录错误 CRITICAL logging.critical() 表示致命错误
4.3 禁用日志
logging.disable() :禁用在这行代码之后的所有信息
import logging
logging. basicConfig(
level= logging. INFO,
format = '%(asctime)s - %(levelname)s - %(message)s' )
logging. critical( "Critical" )
logging. disable( logging. CRITICAL)
logging. critical( "Critical" )
logging. error( "Error" )
4.4 将日志记录到文件
import logging
logging. basicConfig(
filename= "./logging.txt" ,
level= logging. INFO,
format = '%(asctime)s - %(levelname)s - %(message)s' )
logging. critical( "Critical" )
logging. critical( "Critical" )
logging. error( "Error" )