每当代码异常行为且其执行突然停止时,Python都会引发错误和异常。Python通过使用try-except语句的异常处理方法为我们提供了处理此类情况的工具。找到的一些标准异常包括ArithmeticError,AssertionError,AttributeError,ImportError等。
在这里,我们创建了一个新的异常类,即User_Error。需要从内置Exception类直接或间接派生异常。让我们看一下给定的示例,该示例在给定的类中包含构造函数和显示方法。
# class MyError is extended from super class Exception
class User_Error(Exception):
# Constructor method
def __init__(self, value):
self.value = value
# __str__ display function
def __str__(self):
return(repr(self.value))
try:
raise(User_Error("User defined error"))
# Value of Exception is stored in error
except User_Error as error:
print('A New Exception occured:',error.value)输出结果
A New Exception occured: User defined error
当单个模块处理多个不同的错误时,将创建派生类异常。在这里,我们为该模块定义的异常创建了一个基类。此基类由各种用户定义的类继承,以处理不同类型的错误。
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class Dividebyzero(Error):
"""Raised when the input value is zero"""
pass
try:
i_num = int(input("Enter a number: "))
if i_num ==0:
raise Dividebyzero
except Dividebyzero:
print("Input value is zero, try again!")
print()输出结果
Enter a number: Input value is zero, try again!
运行时错误是一个内置类,只要生成的错误未属于上述类别,就会引发该错误。下面的程序说明了如何将运行时错误用作基础类,并将用户定义的错误用作派生类。
# User defined error
class Usererror(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise Usererror("userError")
except Usererror as e:
print (e.args)输出结果
('u', 's', 'e', 'r', 'E', 'r', 'r', 'o', 'r')在本文中,我们学习了如何在Python 3.x中声明和实现用户定义的异常。或更早。