zoukankan      html  css  js  c++  java
  • 异常处理

         当程序运行发生异常时,我们想要的是处理这个异常,而不是将这个异常显示在用户的界面上,我们可以使用try ...except(finally)...来处理异常,下面主要介绍try ...except

    异常处理情况

    1.处理所有异常

    try:
        commands
        commands
    except:
        do someting

    2.处理指定异常

    try:
        commands
        commands
    except IOError:
        do somting

    3.打印异常内容

    任意异常:
    try:
        commands
        commands
    except Exception,e:
        print 'e'
    
    特定异常内容:
    try:
        commands
        commands
    except IOError,e:
        print 'e'

    ps:所有异常的定义都是继承 Exception 。

    自定义异常

    class MyError(Exception):
        def __init__(self,error):
            self.name=error 
        def __str__(self):
            return self.name
    myself=MyError('自定义错误')
    print myself

    手动触发错误( raise ):

    raise MyError('错误')

    except和finally区别:

    except当执行代码的过程中有执行,执行except下面的命令行,无异常时不执行。 

    finally  不管代码是否有异常,最后都会执行finally内的代码块。

  • 相关阅读:
    mysql插入中文数据变成问号怎么处理
    项目第二阶段
    项目第一阶段
    项目测试
    常用mysql操作
    常用的mysql操作
    mysql操作
    土地档案管理系统需求分析
    土地档案管理系统架构图,ER图,用例图
    Load data local infile
  • 原文地址:https://www.cnblogs.com/white-small/p/6343981.html
Copyright © 2011-2022 走看看