简体   繁体   English

如何处理在异常处理程序中引发的自定义异常?

[英]How to handle a custom exception raised inside an exception handler?

If I run the following Python script and assuming that my file read will fail, the IOError handler will raise a custom exception, but I am not sure as to how should I handle the custom exception raised. 如果我运行以下Python脚本并假设我的文件读取将失败,则IOError处理程序将引发自定义异常,但是我不确定应如何处理所引发的自定义异常。 Can anyone please help? 谁能帮忙吗?

class CustomIOError(IOError):
  def __init__(self, msg):
    super(CustomIOError, self).__init__()
    self.error_msg = msg

try:
  # Open file to read
  with open(fileName) as f:
    for line in f:
    print line,
except IOError :
  raise CustomIOError('Exception message')

#  except CustomIOError :
#    sys.exit(0)

Also if Python supports polymorphism, why can't I directly handle an exception of base class, with with an exception handler of derived class? 另外,如果Python支持多态,为什么我不能使用派生类的异常处理程序直接处理基类的异常?

try:
  raise IOError
except CustomIOError:
  pass

This won't work, program execution will terminate after printing a portion of stack trace. 这将不起作用,程序执行将在打印部分堆栈跟踪信息后终止。

Once an exception gets caught by an except clause, any subsequent excepts in the same block are ignored, so you can't do that: 一旦异常被except子句捕获,同一块中的任何后续except将被忽略,因此您不能这样做:

try:
   ...
except Something:
   raise MyError
except MyError: <-- won't work!
  ....

You need another try block around the whole thing: 您需要对整个过程进行另一次try

try:

    try:
       ...
    except Something:
       raise MyError

except MyError: <-- will work
   ...

For the second question, it works another way round: 对于第二个问题,它的工作方式却相反:

try:
  raise CustomIOError
except IOError: <-- works
  pass

This is because CustomIOError is an IOError , but IOError is not CustomIOError (compare: dog is an animal, but (any) animal is not a dog), so your except doesn't match. 这是因为CustomIOErrorIOError ,但是IOError不是CustomIOError (比较:dog是动物,但(any)动物不是狗),因此您的except不匹配。

In general, custom exceptions provide a way to wrap generic errors into application-specific ones, so that the high-level code doesn't have to deal with all error details when something goes wrong. 通常,自定义异常提供了一种将通用错误包装到特定于应用程序的异常中的方法,这样,当发生错误时,高级代码不必处理所有错误细节。 For example, you have a function that reads a file and writes the content to a sql database. 例如,您具有一个读取文件并将内容写入sql数据库的功能。 The code that invokes this function only wants to know if it succeeds or fails, details are irrelevant (although they should be logged for investigation later on). 调用此函数的代码仅想知道它是成功还是失败,细节无关紧要(尽管以后应记录下来以进行调查)。 So, the function just throws one exception to indicate that it failed: 因此,该函数仅引发一个异常以指示其失败:

# higher-level code

class UserInterface:

     def writeButtonClick:
        try:
            readAndWrite()
        except ReadAndWriteFailure:
            showMessage("Problem! Please try again") 

# lower-level code

class ReadAndWriteFailure(Exception):
    pass

def readAndWrite():
   try:
       fp = open(someFile)
       db = sql.connection()
       for line in fp:
          db.execute(line)
   except IOError:
      log it
      raise ReadAndWriteFailure()
   except SQLError:
      log it
      raise ReadAndWriteFailure()
   etc
  1. expect sub type cant catch a super type error 期望子类型无法捕获超级类型错误
  2. the exception throws from except part A cant be catch by the except part next to A 从A部分以外的异常引发的异常不能被A旁边的异常部分捕获

So if catch IOError , throw CustomIOError and handle that CustomIOError is what you want. 因此,如果捕获IOError,则抛出CustomIOError并处理您想要的CustomIOError You can use a try...except block outside the IOError block 您可以在IOError块之外使用try ... except块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM