将异常子类化有什么帮助?

2024-10-02 02:44:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我没有直接调用异常,而是看到它是子类化的,没有任何内容或pass语句。它如何帮助Python以这种方式在内部对基类进行子类化?它是否更改了名称空间或签名?怎么做

class ACustomException(Exception):
    pass

class BCustomException(Exception):
    pass

Tags: 名称内容方式exception空间pass语句基类
3条回答

它有助于确定回溯问题所指的“什么”,以防您可能正在运行的web服务,因此它不是低级错误或通常返回的一般错误,而是将要使用的异常类

更具体地说,举个例子:

val = int(input('Enter a number:'))
try:
  val *= val
except ValueError as e:
  raise e
print(val)

### ValueError will be raised if user inputs something other than a number
### this raise e will return the actual error message saying 
### ValueError: invalid literal for int() with base 10: 'ok'

在您的情况下,您仍然可以将ValueError保留为要处理的异常,如下所示:

val = int(input('Enter a number:'))
try:
  val *= val
except ValueError as e:
  raise ACustomException('some debug statement referring to the cause of the error')

print(val)

### now this will raise your exception class besides the ValueError exception, with a debug statement if you choose to have one in it.

提出Exception就像告诉医生“有什么不对劲”,然后拒绝回答任何问题。比较:

try:
    with open("foo.json", "rt") as r:
        new_count = json.load(r)["count"] + 1
except Exception:
    # Is the file missing?
    # Is the file there, but not readable?
    # Is the file readable, but does not contain valid JSON?
    # Is the file format okay, but the data's not a dict with `count`?
    # Is the entry `count` there, but is not a number?
    print("Something's wrong")
    # I don't care. You figure it out.

try:
    with open("data.json", "rt") as r:
        new_count = json.load(r)["count"] + 1
except FileNotFoundError:
    print("File is missing.")
except PermissionError:
    print("File not readable.")
except json.decoder.JSONDecoderError:
    print("File is not valid JSON.")
except KeyError:
    print("Cannot find count.")
except TypeError:
    print("Count is not a number.")

如果您正在创建一个库,您可以在适当的地方使用预定义的异常类,但有时您需要传达Python创建者从未想到的错误,或者您需要比现有异常做更精细的区分。这是创建自定义异常的时间

例如,Django将定义django.contrib.auth.models.User.DoesNotExist异常,以告知代码试图在数据库中查找User,但找不到与给定条件匹配的User。能够捕捉django.contrib.auth.models.User.DoesNotExist就像是一名医生,让一名患者不仅告诉你什么是伤害,还带来X光片和打印的家族史

当您使用try-except处理异常时,您将按名称捕获异常,因此使用特定名称有助于您处理异常

例如,如果函数因任何错误而引发Exception,则捕获逻辑将变得复杂:

def foobar():
    if FOO:
        raise Exception('FOO happened')
    elif BAR:
        raise Exception('BAR happened')

try:
    foobar()
except Exception as e:
    if e.args == ('FOO happened',):
        print('Handling FOO')
    elif e.args == ('BAR happened',):
        print('Handling BAR')
    else:
        raise

另一方面,如果您有子类异常,捕获逻辑很简单:

class FooError(Exception):
    pass

class BarError(Exception):
    pass

def function():
    if FOO:
        raise FooError('FOO happened')
    elif BAR:
        raise BarError('BAR happened')

try:
    function()
except FooError:
    print('Handling FOO')
except BarError:
    print('Handling BAR')

相关问题 更多 >

    热门问题