1

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.

We can call the main class the Manager and the classes I want to save in files can be called 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). 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? 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.

Daniel Oliveira
  • 1,280
  • 14
  • 36
  • 1
    Do what `HashMap` does. Return the old value associated with the key, or null if there wasn't one. You don't need an exception. – user207421 Nov 18 '16 at 20:10
  • @EJP In this situation I don´t want to return a reference to any object. Since I want to save the object in memory the function would return true if the object was saved with success or false if it didn´t exist or if some IOException occurred. – Daniel Oliveira Nov 18 '16 at 20:13
  • 1
    You should probably not be thinking too much about performance but about the conditions in which exceptions are the appropriate design and implementation choice. Look at the standard APIs themselves, do they use exceptions they way you describe? Etc. – pvg Nov 18 '16 at 20:13

2 Answers2

1

Exceptions are used if there is nothing you can do like writing a file to disk but the disk is full.

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.

Exceptions are more expensive than if because when the exception is raised it creates stacktrace to walk back.

So, if you can do anything to avoid an error, use if. If you can't, then use exception

SkrewEverything
  • 2,393
  • 1
  • 19
  • 50
1

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.

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.

Community
  • 1
  • 1
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142