📜  如何将参数传递给Python中的异常?

📅  最后修改于: 2022-05-13 01:54:50.279000             🧑  作者: Mango

如何将参数传递给Python中的异常?

可能会出现需要从Python引发的异常中获取额外信息的情况。
Python有两种类型的异常,即内置异常和用户定义的异常。
为什么在异常中使用参数?
在Python中使用异常参数很有用,原因如下:

  • 它可用于获取有关遇到的错误的附加信息。
  • 由于 Argument 的内容可能会根据Python中不同类型的异常而有所不同,因此可以将变量提供给异常以捕获遇到的错误的本质。相同的错误可能由不同的原因发生,参数帮助我们使用except子句识别错误的具体原因。
  • 它也可以用来捕获多个异常,通过使用一个变量来跟随异常的元组。

内置异常中的参数:

下面的代码演示了使用带有内置异常的参数:
示例 1:

Python3
try:
    b = float(100 + 50 / 0)
except Exception as Argument:
    print( 'This is the Argument\n', Argument)


Python3
my_string = "GeeksForGeeks"
 
try:
    b = float(my_string / 20)
except Exception as Argument:
    print( 'This is the Argument\n', Argument)


Python3
# create user-defined exception 
# derived from super class Exception
class MyError(Exception):
   
    # Constructor or Initializer
    def __init__(self, value):
        self.value = value
   
    # __str__ is to print() the value
    def __str__(self):
        return(repr(self.value))
   
try:
    raise(MyError("Some Error Data"))
   
# Value of Exception is stored in error
except MyError as Argument:
    print('This is the Argument\n', Argument)


Python3
# class Error is derived from super class Exception
class Error(Exception):
 
    # Error is derived class for Exception, but
    # Base class for exceptions in this module
    pass
 
class TransitionError(Error):
 
    # Raised when an operation attempts a state
    # transition that's not allowed.
    def __init__(self, prev, nex, msg):
        self.prev = prev
        self.next = nex
 
try:
    raise(TransitionError(2, 3 * 2, "Not Allowed"))
 
# Value of Exception is stored in error
except TransitionError as Argument:
    print('Exception occurred: ', Argument)


输出:

This is the Argument
 division by zero

示例 2:

Python3

my_string = "GeeksForGeeks"
 
try:
    b = float(my_string / 20)
except Exception as Argument:
    print( 'This is the Argument\n', Argument)

输出:

This is the Argument
 unsupported operand type(s) for /: 'str' and 'int'

用户定义的异常中的参数:

下面的代码演示了如何使用带有用户定义异常的参数:
示例 1:

Python3

# create user-defined exception 
# derived from super class Exception
class MyError(Exception):
   
    # Constructor or Initializer
    def __init__(self, value):
        self.value = value
   
    # __str__ is to print() the value
    def __str__(self):
        return(repr(self.value))
   
try:
    raise(MyError("Some Error Data"))
   
# Value of Exception is stored in error
except MyError as Argument:
    print('This is the Argument\n', Argument)

输出:

This is the Argument
 'Some Error Data'

示例 2:

Python3

# class Error is derived from super class Exception
class Error(Exception):
 
    # Error is derived class for Exception, but
    # Base class for exceptions in this module
    pass
 
class TransitionError(Error):
 
    # Raised when an operation attempts a state
    # transition that's not allowed.
    def __init__(self, prev, nex, msg):
        self.prev = prev
        self.next = nex
 
try:
    raise(TransitionError(2, 3 * 2, "Not Allowed"))
 
# Value of Exception is stored in error
except TransitionError as Argument:
    print('Exception occurred: ', Argument)

输出:

Exception occurred:  (2, 6, 'Not Allowed')