Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which exception to throw when I find my data in inconsistent state in Scala?

I have a small Scala program which reads data from a data source. This data source is currently a .csv file, so it can contain data inconsistencies.

When implementing a repository pattern for my data, I implemented a method which will return an object by a specific field which should be unique. However, I can't guarantee that it will really be unique, as in a .csv file, I can't enforce data quality in a way I could in a real database.

So, the method checks whether there are one or zero objects with the requested field value in the repository, and that goes well. But I don't know Scala well (or Java for that matter), and the charts of the Java exception hierarchy which I found were not very helpful. Which would be the appropriate exception to throw if there are two objects with the same supposedly unique value. What should I use?

like image 818
rumtscho Avatar asked Apr 20 '14 13:04

rumtscho


People also ask

How do you throw an exception in Scala?

In scala, throwing an exception is the same as Java. we create an exception object and then we throw it with the throw keyword: Example: Scala.

How to handle Error in Scala?

A basic way we can handle exceptions in Scala is the try/catch/finally construct, really similar to the Java one. In the following example, to make testing easier, we'll return a different negative error code for each exception caught: def tryCatch(a: Int, b: Int): Int = { try { return Calculator.

Does Scala have exceptions?

Because functional programming is like algebra, there are no null values or exceptions.


1 Answers

There are two handy exceptions for such cases: IllegalStateException and IllegalArgumentException. First one is used when object internal state is in some illegal position (say, you calling connect twice) and the last one (which seems to be more suitable to your case) is used when there is the data that comes from the outside world and it does not satisfy some prescribed conditions: e.g. negative value, when function is supposed to work with zero & positive values.

Both are not something that should be handled programmatically on the caller side (with the try/catch) -- they signify illegal usage of api and/or logical errors in program flow and such errors has to be fixed during the development (in your case, they have to inform developer who is passing that data, that specific field has to contain only unique values).

like image 152
om-nom-nom Avatar answered Oct 03 '22 11:10

om-nom-nom