为什么最好不要在通用类中捕获异常? [英] Why is it best to not catch exceptions in general-purpose classes?

查看:113
本文介绍了为什么最好不要在通用类中捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您为某些通用目的使用类时,为什么最好不要捕获异常?

When you implement a class for some general-purpose use, why is it best not to catch exceptions?

我想是这样,错误可以上升堆栈和帮助在调试过程中。任何其他原因?

I suppose it's so that the error can go up the stack and help in the debugging process. Any other reasons?

推荐答案

此规则应更好地阅读:不要处理您不知道如何处理的异常!

This rule should better read: Do not handle Exceptions you do not know how to handle!

如果例如您写一个类读取CSV文件并返回行的标记,您将在类中有一些可能抛出IOException的点。你一定不能抓住它,因为处理它并不是你的责任!您的任务是将一串字节转换成令牌流,没有更多。如果有人将损坏的流传给你,这应该由他处理,而不是你处理。

If e.g. you write a class that reads a CSV file and return the tokens of the line, you will have some points in your class where an IOException might be thrown. You should definitely not catch it, because it is just not your responsibility to handle it! Your task is to convert a stream of bytes into a stream of tokens, nothing more. If someone passes a corrupt stream to you, this should be handled by him, not you.

编辑:另一个例子:如果你的库示例到达SocketException,并且套接字已经从调用者给予了lib,然后传递SocketException。如果你的库只是一个抽象的连接框架,那么也可以连接到文件,内存等,而SocketExceptions并不常见,将它们包装在一个ConnectionException中。

EDIT: Another example: If your library for example reaches a SocketException, and the socket has been given to the lib from the caller, then pass the SocketException up. If your library is just an abstract connection framework, that could also connect to files, memory etc., and SocketExceptions are not common, wrap them in a ConnectionException.

这篇关于为什么最好不要在通用类中捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆