[英]Should I use exceptions in cases like this?
Imagine that I have a main class that handles an HashMap of another type of class that I want to store in files using the interface serializable. 想象一下,我有一个主类,该主类处理要使用可序列化接口存储在文件中的另一种类型的HashMap 。
We can call the main class the Manager and the classes I want to save in files can be called Data . 我们可以将主类称为Manager ,而我要保存在文件中的类可以称为Data 。
Now, the Manager class has a method to save an instance of the Data class into a file (all instances of Data are stored in a HashMap in the Manager class). 现在, Manager类具有一种将Data类的实例保存到文件中的方法(所有Data实例都存储在Manager类的HashMap中)。 The name of the instance is entered my the user so it may not exists.
用户输入了实例的名称,因此它可能不存在。
What should I do in cases like this? 在这种情况下该怎么办? Check if the instance exists and if not I return false or make a function that returns void and throws an exception if the instance does not exists?
检查实例是否存在,如果不存在,我返回false或使函数返回void并在实例不存在时引发异常? Should I use exceptions in cases like this?
在这种情况下我应该使用例外吗? Will exceptions make a big impact in the performance of a program (since every time we throw one we have to create a new object...)?
异常会对程序的性能产生重大影响吗(因为每次抛出一个异常,我们都必须创建一个新对象...)?
Thanks. 谢谢。
Exceptions
are used if there is nothing you can do like writing a file to disk but the disk is full. 如果无法执行任何操作(例如将文件写入磁盘但磁盘已满),则使用
Exceptions
。
if
are used if you can do something like checking the denominator is zero or not in division and asking the user to input another number. if
可以执行诸如检查分母为零或不除以要求用户输入其他数字的操作,则使用if。
Exceptions
are more expensive than if
because when the exception is raised it creates stacktrace to walk back. Exceptions
要比if
发生异常时要昂贵得多if
因为当引发异常时,它会创建堆栈跟踪以向后走。
So, if you can do anything to avoid an error, use if
. 因此,如果您可以做任何避免错误的操作,请使用
if
。 If you can't, then use exception
如果不能,请使用
exception
You need to throw an exception in a case when that case breaks further program's logic. 当这种情况破坏了进一步的程序逻辑时,您需要抛出一个异常。
If the instance existence is significant and important for the future operations, then you'd better throw an exception. 如果实例的存在对于将来的操作很重要且很重要,那么最好抛出一个异常。 Otherwise, the method could return a
boolean
without any exceptions. 否则,该方法可以返回一个
boolean
而没有任何异常。
Will exceptions make a big impact in the performance of a program?
异常会对程序的性能产生重大影响吗?
No, they won't. 不,他们不会。 Anyway, you shouldn't be anxious about that.
无论如何,您不应该为此担心。
There are a good question and answers. 有一个很好的问题和答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.