First of all, I know that the standard answer will be that exceptions to control flow are never used. Although I completely agree with this, I thought for a long time about what I sometimes did, which I will discuss with the following pseudo-code:
try string keyboardInput = read() int number = int.parse(keyboardInput) //the conversion succeeds if(number >= 1000) //That not what I asked for. The message to display to the user //is already in the catch-block below. throw new NumberFormatException() //well, there IS something wrong with the number... catch(NumberFormatException ex) //the user entered text print("Please enter a valid number below 1000.")
First of all, take the example of a very abstract way. This does not have to happen. The situation is simple:
User input should be limited and may go wrong in two ways, or with an abandoned exception defined by language, or by check. Both errors are reported by the user in the same way because they do not need to know the technical difference in what caused it.
I thought of several ways to solve it. To begin with, it would be better to throw a custom exception. The problem I am facing is that if I catch it locally, what should I do with the other exception? As a result of this, a custom exception would be the cause of the second catch block, in which the message would be copied just as well. My decision:
//number is wrong throw new MyException() catch(NumberFormatException ex) throw new MyException() catch(MyException ex) { print("Please enter...")
The meaning of exception names is everything here. This application of specially made exceptions is widely accepted, but essential . I did not do anything else at first glance: I have to go into the blocking block, although throwing a custom exception, not a standard library one.
Just like using an exception for the calling method (nor does it have a catch block for a custom exception) seems to make more sense. My method may be mistaken in that technically in two ways, but essentially in one way: by incorrect user input. Therefore, you should write a UserInputException
and make the method throw it. New issue: what if this is the main application method?
Currently, I am not struggling with a specific application to implement this behavior, my question is purely theoretical and non-linguistic.
What is the best way to approach this?