python-lhc005-异常

异常
在运行代码的过程当中,如果代码出现错误,便会引起程序错误而导致闪退或者崩溃,极大影响了用户的使用体验,因此我们需要捕捉异常,从而不令程序崩溃。

try:
   print(num)
except:
  print('捕捉到了异常')                         # 由于num没有赋值,所以程序会出错,但我们设置了except,捕捉到了异常并执行except下的操作,避免了程序报错
try:
   print(num)
   open('ss.txt','r')
except Exception as e:
  print(e)                                     # 当发生异常后会寻找except,所以执行完print(num)后便不会执行open而是直接执行了except。  except Exception as e: 捕捉所有类型的异常并将异常信息赋值给临时变量e。

name ‘num’ is not defined 这个是以上代码输出后的结果

try :
    print(num)
except Exception as k:            # 捕捉到了异常运行则运行      except
    print('捕捉到了异常',k)
else:                             # 没有捕捉到异常运行则运行     else
    print('hello')
finally:                          # 无论是否捕捉到异常都会运行    finally
    print('finally')

以上是 except, else,finally

自定义异常类

class AgeError(Exception):
  def __init__(self, age):
    self.__age = age

  def __str__(self):
    return "您输入的年龄不符合业务需求age=%d" % self.__age

class Person(object):
  def __init__(self, name, age):
    if age > 0 and age < 150:
        self.name = name
        self.age = age
    else:
        # 抛出自定义异常
        raise AgeError(age)

xm = Person("小明", 311)

当我们要创建对象时,创建的对象不符合我们的要求,我们不想创建它,但它并不时一个程序上错误或语法错误,所以系统不会检测出错误并报错,于是我们要定义一个自定义异常来进行报错并且不创建这个对象。
以上代码中就用到了 ‘raise’ 来抛出给我们创建好的异常类AgeError

猜你喜欢

转载自blog.csdn.net/qq_42084094/article/details/82813532
005