TypeError:exception必须是旧式类或派生自BaseException,而不是str

1 python exception

我是OS X 10.8上运行2.7.6的Python初学者,添加了numpy和pyobjc.这是我正在尝试运行的脚本:

from __future__ import with_statement
from Foundation import NSMutableDictionary, NSUserDefaults, NSCFArray, objc
import numpy as np
from copy import copy
import os
import re

domainName = "org.mworks-project.MWClient"

outFile = os.path.expanduser(os.path.join('~/Desktop','org.Behavior.MWClientSavedVars.plist'))
keyNames = [ 
  'MATLAB client window - selected variables',
  'MATLAB client window - MATLAB .m file',
  'recentPythonScripts' ]

homedir = os.getenv('HOME')

################

def subStr(inStr):
    return re.sub('^%s'%homedir, '$HOME', inStr)

def replaceUserdirWithStr(inObj):
    if type(inObj) == str or type(inObj) == objc.pyobjc_unicode:
        return subStr(inObj)
    elif isinstance(inObj, NSCFArray):
        for i in range(len(inObj)):
            # do this recursively
            inObj[i] = replaceUserdirWithStr(inObj[i])
        return inObj
    else:
        print type(inObj)
        #import pdb; pdb.set_trace()
        raise 'Error: Type unknown'
    return 

################

# get client defaults
standardUserDefaults = NSUserDefaults.standardUserDefaults()
clientDefs = standardUserDefaults.persistentDomainForName_(domainName)

# copy the fields we need
writeDict = NSMutableDictionary.dictionary()
for k in clientDefs:
  if k in keyNames:
    tVal = clientDefs[k]
    tVal = replaceUserdirWithStr(tVal)
    writeDict[k] = tVal
success = writeDict.writeToFile_atomically_(outFile, 1)
############################################################
Run Code Online (Sandbox Code Playgroud)

尝试运行此脚本但遇到此错误时:

<objective-c class __NSCFArray at 0x7fff7b9ea3c0>
Traceback (most recent call last):
  File "nameOfTheFileHere.py", line 60, in <module>
    tVal = replaceUserdirWithStr(tVal)
  File "nameOfTheFileHere.py", line 45, in replaceUserdirWithStr
    raise 'Error: Type unknown'
TypeError: exceptions must be old-style classes or derived from BaseException, not str
Run Code Online (Sandbox Code Playgroud)

我很难过.有没有人知道这方面的方法?

mhl*_*ter 6

这条线

raise 'Error: Type unknown'
Run Code Online (Sandbox Code Playgroud)

是无效的,因为你试图提出一个str而不是一个Exception

你想做更像的事情:

raise TypeError('Type unknown')
Run Code Online (Sandbox Code Playgroud)

我假设TypeError只是因为你的消息是"Type unknown"

有关更多信息,请阅读有关引发异常的文档:http: //docs.python.org/2/tutorial/errors.html#raising-exceptions