python异常处理 try,except,finally

1、基本语法
在python中,一般处理和捕获异常会用到这个结构:

try:
	python程序
except 错误类型1:
	python程序
except 错误类型2:
	python程序
except 其他错误类型:
	python程序
finally:
	python程序
  1. 首先一定会进入try中执行try的python程序
  2. 如果报错
    1. 则进入except 相应的错误类型,然后执行except的python程序
    2. 然后进入finally,执行finally的python程序
  3. 如果不报错
    1. 进入finally,执行finally的python程序

2、leetcode实例

tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
def evalRPN(self, tokens):
	hash_dic = {
    
     "+": add, "-": sub, "*": mul, "/": lambda x, y: int(x / y)}
	stack_list = []
	for token in tokens:
	    try:	        
	        num = int(token)
	    except ValueError:	        
	        num2 = stack_list.pop()
	        num1 = stack_list.pop()
	        num = hash_dic[token](num1, num2)
	    finally:
	        stack_list.append(num)
	    
	return stack_list[0]

现在我们有一个tokens数组,数组的元素是数字字符串,或者是代表加减乘除操作的字符(即’+‘、’-‘、’‘、’'),现在要让tokens的元素按照逆波兰表示法进行运算

  1. 首先我们有很多个tokens数组会进入这个函数中进行处理
  2. evalRPN函数,专门进行逆波兰式子的计算,传进来tokens数组
  3. 将代表加减乘除操作的字符做出hash表对应起来
  4. 创建一个栈
  5. 遍历这个数组的元素得到单个token
  6. 用try来判断这个token是不是数字,不是就进行except
  7. 不是数字,那么就是运算符,进行出栈操作,将出栈的两个元素和运算符进行计算得到结果
  8. 如果token是数字,就直接进栈,不是数字,将except的运算结果进栈

猜你喜欢

转载自blog.csdn.net/weixin_50592077/article/details/133069885