objects throwing exceptions inside of objects

2019-06-13 17:29发布

I'm working on an object that at some point instantiates another object. That inner object might throw an exception. I could just let that exception bubble up to whatever code is handling the parent object, which is what I want to do, following the philosophy of KISS. Or, I could do some exception handling within the parent object, and perhaps give a more meaningful exception to the 'client' code. Is there a general rule to follow, or do I decide what to do on a case-by-case basis?

With the child object, I took the time to write error codes, so at some point in the future I could give the end-user a more meaningful error message. If the parent object and the child object have their own set of error codes, how do I handle that? It seems I would write an exception handler that looks at the error code and its originating class, right?

2条回答
一夜七次
2楼-- · 2019-06-13 18:00

Assuming the outer object could not handle the Exception, I would only catch and rethrow it as a different Exception if there was a good reason to hide the inner object. You don't want all of your code to depend on the internals of something that doesn't need to be exposed.

Other than that, if the outer object doesn't know what to do or has nothing to add, it shouldn't really touch the exception.

查看更多
地球回转人心会变
3楼-- · 2019-06-13 18:06

If the "outer" object cannot handle the exceptions thrown by the "inner" object then it must not try to. At best it can catch a few of the more common ones and rethrow with slightly more information attached.

查看更多
登录 后发表回答