简体   繁体   English

python json序列化try / except

[英]python json serialization try/except

I'm trying to serialize a trivial object (only attributs / values), I have this methode in my class. 我正在尝试序列化一个琐碎的对象(仅属性/值),我的课堂上有这个方法。

def to_json(self,client):
    service=self._service
    path="jsonphp/"
    path+=client
    if not os.path.exists(path):
        os.makedirs(path)
    with cdd(path):
      print os.getcwd()
      path=service+".json"
      with open(path, 'w') as outfile:
        try:
          json.dump(self.__dict__, outfile)
        except:
          print "serialization failed"

the whole part before the try/except is to naviguate to the correct folder. try / except之前的整个部分是导航到正确的文件夹。 It seems to work smoothly. 看来工作顺利。 But when I use this methode, it always print : serialization failed from my except even tho my file.json is created and the data are correctly stored in it : {"_attr1": "On", "_attr2": "On", "_attr3": "Off"} I thought the except block was only visited if an error had occured. 但是,当我使用这种方法时,它始终会打印: serialization failedexcept创建了file.json并且数据已正确存储在其中: {"_attr1": "On", "_attr2": "On", "_attr3": "Off"}我以为只有在发生错误时才访问except块。

My questions are the fallowing : is that the "normal" behaviour of try/except ? 我的问题是休假: try/except的“正常”行为吗?

If not, how to have information about the exception that my except is catching ? 如果不是,如何获取有关我的except正在捕获的异常的信息?

Could it be an exeption from somewhere upper in the code (before I call to_json() ) that is catched there ? 难道是从代码中较高处(在我调用to_json() )被to_json()吗?

I find this to be more of an exception handling question than anything else. 我发现这比其他任何事情更像是一个异常处理问题。 Since you're likely to have exceptions throughout your programming endeavors, it's important to handle them properly. 由于您可能在整个编程工作中都会遇到异常,因此正确处理它们很重要。 Rarely should the except be so broad, and in the case where you don't understand why there is an exception, you should be printing the exception. 例外情况很少这么广泛,并且在您不了解为什么会有例外的情况下,应该打印例外。 This will give you the ability to search for the exception and determine what the root cause of your problem is and will help you greatly as you continue to learn Python. 这将使您能够搜索异常并确定问题的根本原因是什么,并且在您继续学习Python时会大有帮助。

Change your except to read: 将您的除外更改为:

except Exception as e:
          print "serialization failed", e

This will print the exact exception to your console and allow you to look up, or ask for help. 这会将确切的异常打印到您的控制台,并允许您查找或寻求帮助。

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

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