开发者

Using Exception class only as a transport mechanism?

开发者 https://www.devze.com 2023-02-14 14:33 出处:网络
I\'m unsure if this is a great idea and want to query the community. What about using Exception instances only for transport of data and not throwing them?It\'s for a situation I need to p开发者_如何转

I'm unsure if this is a great idea and want to query the community. What about using Exception instances only for transport of data and not throwing them? It's for a situation I need to p开发者_如何转开发ass exception information in a container of some kind for the purpose of logging or reporting. The data structure of the Exception just happens to be similar to information I need to pass in my program, so I'm considering piggybacking on it.

Exception instances are a handy means to package up information about an exceptional case that doesn't necessarily need to be thrown. For example, exceptional data to be returned as status info (e.g. XML) as response to a web service call into the app. I don't need to invoke the exception handling system and its resources to do this.

What's good is the Exception class is understood at all levels of apps (in System namespace) so it can be used as a container without referencing in another assembly or without creating a custom class. Also Exceptions can be treated as normal objects, like being return values of methods, and don't need to be thrown.

Plus the app can choose to start throwing them if it ever wishes, I suppose.


The main problem I would see with this would be the confusion it could cause the consumers of your code.

They see an Exception object being created and passed around but not thrown. This would confound their expectations.

You could create your own class based on Exception and use that, but again it seems a little "clunky" to me.


Might seem a little confusing, but otherwise I don't see a problem. Another solution might be to create a shared framework dll that is available to all your projects and create a common class there. Possibly also create methods to be able to cast it to an Exception.


What's wrong with throwing them, catching and then logging?
This is how they are supposed to work.

If you throw and catch exceptions in normal way, you will keep the stack trace. Finding mistakes in code without stack traces is a royal pain in the arse.

And you shouldn't use general Exception class, use derived classes, or create your own. I know it takes some time but it will pay for itself when tracing code issues.

0

精彩评论

暂无评论...
验证码 换一张
取 消