python 如何捕获参数异常?

有这个函数:

def hello(msg):
    print('hello'+msg)

假设现在我在调用 hello 时不传递 msg 参数, 那么Python 会抛出 TypeError 异常.

有没有什么办法能在 hello 函数中捕获这个异常呢?

阅读 5.2k
4 个回答

谢谢大家, 刚刚找到答案了, 可以用装饰器实现, 先定义个 check 装饰器:

import traceback
import sys

def check(method):
    '''
    check argument
    '''
    def wrapper(*args, **kw):
        try:
            return method(*args, **kw)
        except TypeError:
            print("I catch you!")
            stack = traceback.format_list(traceback.extract_stack())
            for line in stack:
                print('>> '+line.strip())
            print(sys.exc_info())

    return wrapper

然后还要把 hello 函数添加上装饰器:

@check
def hello(msg):
    print(msg)

test

try:
    hello()
except TypeError:
    print('出错了')

题主要求在hello函数中捕获这个异常:
可以试试:

def hello(msg = None):
    if msg==None:
        raise Exception("TypeError")
    print('hello'+msg)

建议用楼上的方法

异常只能是从内向外传递,TypeError 是调用函数引起的, 并不是因为函数内部引起的,

综上所述,个人觉得这个异常没法在函数内部捕获。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题