python未知错误中的异常

时间:2013-10-29 18:22:31

标签: python

      except ValueError:
        print "the input is Invaild(dd.mm.year)"
    except as e:
        print "Unknown error"
        print e

这是我写的代码,如果错误不同然后会发生valueerror,它会在e中打印吗? 感谢

2 个答案:

答案 0 :(得分:6)

您需要抓住BaseExceptionobject此处才能分配给e

except ValueError:
    print "the input is Invaild(dd.mm.year)"
except BaseException as e:
    print "Unknown error"
    print e

或者,更好的是Exception

except ValueError:
    print "the input is Invaild(dd.mm.year)"
except Exception as e:
    print "Unknown error"
    print e

一揽子except:将抓住与BaseException相同的例外情况,仅抓住Exception忽略 KeyboardInterruptSystemExit,和GeneratorExit。没有抓住这些,通常是一个好主意。

有关详细信息,请参阅exceptions documentation

答案 1 :(得分:1)

不,该代码会抛出SyntaxError

如果您不知道代码可能引发的异常,则只能捕获Exception。这样做将获得所有内置的,非系统退出的例外:

except ValueError:
    print "the input is Invaild(dd.mm.year)"
except Exception as e:
    print "Unknown error"
    print e
相关问题