tags: exceptions

Action executed in 0.000

Each Tag

exceptions

Common tags - number of posts

users (1), handling (1), software (1), programming (1), Java (1),

Target Audience

homme, You're right. Software intended for a common user should handle exceptions. I failed to explain that the software i write is usually for my own use, either at home or work. If i find some time, unlikely, i'll post a more thorough example.
parent post: Too short
notify me: yes

Exceptions

What's wrong with this code? I'm not talking about the indenting style or casing.

If you haven't figured it out by now, it's the catch block. It does nothing. So called "software developer" may understand exceptions, but they don't understand the purpose of catching exceptions.

Let's assume your code or the code you call throws an exception. You have 3 options. (1) handle it, (2) don't handle it, (3) catch it and rethrow an exception.

(1) Let's say you're asking for a person's age. If the user enters "1O" (that's an oh not a zero), this should throw an exception when you convert it to a number. More importantly, the way you handle it is by reprompting, maybe 3 times.

(2) You can outright ignore it. In this case you must declare that you may throw it in the function signature. This is perfectly acceptable. In software, where input is not person-generated, for example reading a CSV file from a client, it's best to let that exception trickle right up through main and out to the developer. This is assuming you don't have to close files or database connections. At least this way YOU KNOW, there is a problem with the data. You can then edit the CSV and repair it. Or if the data is correct you can correct your code.

(3) There are cases, when you are implementing an interface or extending a class, that you can't change the function signature. Eg. public void HttpServlet.doGet( HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException. What happens if a NumberFormatException NFE occurs in this function? You must catch it. You should also throw a new ServletException( NFE ). This constructor specifies that NFE is the cause of our servlet exception.

The worst thing to do is, catch the exception and do nothing about it. This will hide errors in your data or your code.

Back to our age example... After 3 times, you've done all you can do to get the age. What should happen after the 4th time? You should catch the NumberFormatException, and throw a new Exception( "User is dumb.", NFE ). Let your callee handle it.