Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to provide exception handling

 
Kendall Ponder
Ranch Hand
Posts: 205
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a question on the practice exam cd which comes with the Sierra & Bates book which asks when you should provide exception handling code. The answers were" when accessing data files" (which I picked) and "when verifying user input" (which I didn't). If you use the Scanner class can't you guarantee correct data with a loop and logic? The book says the general rule is to provide exception handling for things outside the programs control (missing files, etc). It seems to me I can control the input by checking it as it is entered. Thanks!
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kendall Ponder wrote:If you use the Scanner class can't you guarantee correct data with a loop and logic? The book says the general rule is to provide exception handling for things outside the programs control (missing files, etc). It seems to me I can control the input by checking it as it is entered. Thanks!

True! But the (big) question here is: can you always use the Scanner class to process user input. You need a delimiter pattern to write a loop and logic to process the data correctly. What if you have to process a fixed-length file (or input)? So you don't have delimiters, but the 1st 5 characters represent the customer number, followed by 32 characters for the customer first name,...

And a more straightforward example: what if you write a program which uses the command line arguments as input for the program (e.g. java Sum 10 abc)?

Kind regards,
Roel
 
Guillermo Ishi
Ranch Hand
Posts: 789
C++ Linux Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Intercepting letters entered instead of numbers before they can cause a problem is an example of what the program can check for. Trying to read from a file that doesnt' exist or can't be read is an example of beyond the program' s control.
 
Kendall Ponder
Ranch Hand
Posts: 205
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess I interpreted the question answer to mean you should always provide exception handling (which you do when doing file I/O), but I should have interpreted it to mean it is a case when you might need to provide the handler depending on how the user input is defined. Thanks!
 
Guillermo Ishi
Ranch Hand
Posts: 789
C++ Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In that case I can write anything so it will need an exception handler, so the correct answer is always all of the above
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3817
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is ok for a method to throw an exception after checking that input is not valid (IllegalArgumentException). But I have no idea what it means when it says, " you should provide exception handling code when verifying user input". It is too vague. A badly worded option, imho.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I searched this question in the practice exams myself and after having a look at the other options, it confirms my initial thought. This question focuses more on the appropriate use of exception handling. So which are risky operations which (possibly) require exception handling.

For completeness I add all possible answers, followed with my opinion about adding exception handling:
(a) iterating through array --> no, the developer must make sure the index doesn't go outside the bounds of the array.
(b) performing deep recursion --> no, you never catch an (StackOverflow)Error, just like with an OutOfMemoryError there's no way you can handle an Error appropriately.
(c) accessing data files --> yes, I definitely need some exception handling here. Although I'll do every check possible (does file exist, is file readable/writable,...) it's still possible an I/O exception (e.g. network problem while reading, someone else is writing the file,...) occurs which I can handle gracefully (and notify the user).
(d) verifying user input --> yes, I need exception handling here as well. As a developer I can't control the user's input, so the user can enter anything he/she wants. Even after adding some checks/limitations the user can still enter invalid input, so some exception handling will be useful.
(e) casting reference variables --> no, being the developer I need to make sure a ClassCastException will never occur by using generics all the time and/or using the instanceof operator (when I have to deal with non-generic code).

Hope it helps!
Kind regards,
Roel
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3817
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a fundamental problem with this approach. Most of the time the decision to add exception handling depends on what is the purpose of your method/code and not what operation it does. For example, if you are writing a log method, you may want to just return from the method without throwing out any exception even if there is an IOException internally, which means you have exception handling code inside your log method. But if you are writing a copy method, you may want to propagate the exception to the caller i.e. no exception handling code.

These options are so vague you can make an argument either way.


(a) iterating through array --> no, the developer must make sure the index doesn't go outside the bounds of the array.

There could be a millions reason why you are iterating an array. What if some elements of the array are null? Do you want to do null checks for each element, do you just want to catch NPE and proceed, or do you want to throw it out to the caller? So "iterating through an array" doesn't drive whether you should have exception handling or not. Why you are iterating an array does.


(b) performing deep recursion --> no, you never catch an (StackOverflow)Error, just like with an OutOfMemoryError there's no way you can handle an Error appropriately.

But you could catch it and return a meaningful value depending on what the method is trying to do. Something like "Can't compute, number is too large".


(c) accessing data files --> yes, I definitely need some exception handling here. Although I'll do every check possible (does file exist, is file readable/writable,...) it's still possible an I/O exception (e.g. network problem while reading, someone else is writing the file,...) occurs which I can handle gracefully (and notify the user).

As mentioned above, if you are writing a raw copy method, no exception handling is required. The caller should handle it depending on what it is trying to do. But for a log method, may be you do want exception handling.


(d) verifying user input --> yes, I need exception handling here as well. As a developer I can't control the user's input, so the user can enter anything he/she wants. Even after adding some checks/limitations the user can still enter invalid input, so some exception handling will be useful.

By verifying user input, you are actually avoiding exceptions, so you don't really need exception handler. For example, if your method uses the input for diving a number, you should check whether the input is zero and throw an exception instead of just going ahead with the division, then catching ArithmeticException and then doing forward in your method. Same with a check for user input being null. This is not exception handling.


(e) casting reference variables --> no, being the developer I need to make sure a ClassCastException will never occur by using generics all the time and/or using the instanceof operator (when I have to deal with non-generic code).

How about loading an object from a serialized file? Your method may expect the unserialized object to be of a certain type but it turns out it is not. You have the same three options - check it using instanceof before casting, just cast it and catch the CCE, or just cast it and throw the exception out to the caller if any. Depends on what you are trying to do and not on whether you are casting or not.

HTH,
Paul.

 
Guillermo Ishi
Ranch Hand
Posts: 789
C++ Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I remember seeing the quote in S&B that's being tested on in the OP's quote. It was in the context of ok, I've presented you will all these many possibilities, but which are realistic in ordinary use? The answer was i/o and user input to be taken generally because they are the things that are external to the program that have the potential to screw the program. In general and for typical applications. If you were writing something critical for something that could not be serviced I hope you would try to catch everything that could possibly be caught and try to recover from it. At the other extreme, if you were being forced to write something because it was National Code Day, then nah. But in general....
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Anilprem wrote:There is a fundamental problem with this approach. Most of the time the decision to add exception handling depends on what is the purpose of your method/code and not what operation it does. For example, if you are writing a log method, you may want to just return from the method without throwing out any exception even if there is an IOException internally, which means you have exception handling code inside your log method. But if you are writing a copy method, you may want to propagate the exception to the caller i.e. no exception handling code.

These options are so vague you can make an argument either way.

I totally disagree! I know all the scenarios you described can all be implemented, no objections from the Java compiler. But it does not mean that if something is possible, you should also do it. Many of the scenarios you described to argument either way describe vad, very bad practices. Using exception handling for control flow is a very bad practice. E.g. if elements in your array could be null, you always add a null check. You never catch the NullPointerException and proceed, instead of fixing a programming bug you hide it by using an exception handler.

In Java you have 3 kinds of exceptions:
  • checked exception: an exceptional condition that a well-written application should anticipate and recover from (e.g. the file entered by the user doesn't exist and a FileNotFoundException is thrown)
  • error: an exceptional condition that is external to the application, and that the application usually cannot anticipate or recover from (e.g. out of memory)
  • runtime exception: an exceptional condition that is internal to the application, and that the application usually cannot anticipate or recover from (e.g. invoking a method on a null reference)


  • In a well-written application you'll never expect a), b) and e) to happen, because they (mostly) indicate a programming bug (and should be fixed by the developer). But c) and d) are (mostly) not at the control of the (well-written) application (user can enter anything, can select any file) and thus require exception handling as both can screw up the program badly.

    Kind regards,
    Roel
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Guillermo Ishi wrote:the quote in S&B

    All exam aspirants are BFFs of Kathy & Bert, so we all may use their first names (instead of last names) to refer to their study guide
     
    Paul Anilprem
    Enthuware Software Support
    Ranch Hand
    Posts: 3817
    10
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Roel De Nijs wrote:
    Paul Anilprem wrote:There is a fundamental problem with this approach. Most of the time the decision to add exception handling depends on what is the purpose of your method/code and not what operation it does. For example, if you are writing a log method, you may want to just return from the method without throwing out any exception even if there is an IOException internally, which means you have exception handling code inside your log method. But if you are writing a copy method, you may want to propagate the exception to the caller i.e. no exception handling code.

    These options are so vague you can make an argument either way.

    I totally disagree! I know all the scenarios you described can all be implemented, no objections from the Java compiler. But it does not mean that if something is possible, you should also do it. Many of the scenarios you described to argument either way describe vad, very bad practices. Using exception handling for control flow is a very bad practice. E.g. if elements in your array could be null, you always add a null check. You never catch the NullPointerException and proceed, instead of fixing a programming bug you hide it by using an exception handler.


    This is all good but not relevant to the point I am making, which you have overlooked. The point, again, is whether you perform exception handling i.e. use try/catch block largely depends on the purpose of the method. You are taking a dogmatic approach to what must be done irrespective of the situation. I disagree with that.

    There is a huge disagreement over the checked/unchecked exception business of Java among experts and I am sure you are aware of that. It is not for no reason that C# doesnt make such a distinction. Now, I am not saying that Java is wrong and C# is right. I am saying that it really depends on the situation.

    But I have a feeling we have to agree to disagree here
     
    Paul Anilprem
    Enthuware Software Support
    Ranch Hand
    Posts: 3817
    10
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Roel De Nijs wrote:
    In a well-written application you'll never expect a), b) and e) to happen, because they (mostly) indicate a programming bug (and should be fixed by the developer). But c) and d) are (mostly) not at the control of the (well-written) application (user can enter anything, can select any file) and thus require exception handling as both can screw up the program badly.

    Kind regards,
    Roel

    May be I am misunderstanding what you mean by "require exception handling". When you say "require exception handling", I am assuming that you mean use try/catch blocks. Is that correct? If no, what exactly do you mean by that?
     
    Paul Anilprem
    Enthuware Software Support
    Ranch Hand
    Posts: 3817
    10
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Roel De Nijs wrote: You never catch the NullPointerException and proceed, instead of fixing a programming bug you hide it by using an exception handler.

    This is obviously wrong because not every application crashes and burns the moment it receives a NPE. So obviously, some where it is caught and the application does proceed. Whether NPE is a bug or not depends on what the method is supposed to do.
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Anilprem wrote:This is all good but not relevant to the point I am making, which you have overlooked. The point, again, is whether you perform exception handling i.e. use try/catch block largely depends on the purpose of the method. You are taking a dogmatic approach to what must be done irrespective of the situation. I disagree with that.

    Maybe I focused in previous posts too much on methods and/or I'm not completely understanding what you are disagreeing with, but I'm just talking about the situation on its own, regardless of how it's implemented. Two examples to illustrate:
    1/ I don't want/expect to see exception handling code for iterating through an array (just the iteration part, not the processing of each element. If someone committed code like this, I will be
    The developer should write code to iterate through the array without accessing an element with an invalid index (and thus having to catch the ArrayIndexOutOfBoundsException to recover and continue). He could use the length property of the array or use the enhanced for loop, I don't care. And there could even be some exception handling to process each element, but not just for iterating through an array.
    2/ If I need to access data files, I know I'll definitely need some exception handling at some point in my application. Because files could be deleted, a network error could occur,... The exception handling code could be in the method reading the files or could be handled in some another method or maybe you are working with a framework which let you define an exception handler for a specific exception or ... It doesn't matter: you need to access (or write) data files, you'll need exception handling (sooner or later).

    Paul Anilprem wrote:There is a huge disagreement over the checked/unchecked exception business of Java among experts and I am sure you are aware of that. It is not for no reason that C# doesnt make such a distinction. Now, I am not saying that Java is wrong and C# is right. I am saying that it really depends on the situation.

    But the distinction between checked/unchecked exception is irrelevant for this mock question. It's just about in which situation you should provide exception handling code. It doesn't matter if this exception handling code has to handle a checked/unchecked exception.
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Anilprem wrote:When you say "require exception handling", I am assuming that you mean use try/catch blocks. Is that correct?

    A clean and simple yes
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Anilprem wrote:
    Roel De Nijs wrote: You never catch the NullPointerException and proceed, instead of fixing a programming bug you hide it by using an exception handler.

    This is obviously wrong because not every application crashes and burns the moment it receives a NPE. So obviously, some where it is caught and the application does proceed. Whether NPE is a bug or not depends on what the method is supposed to do.

    True!

    But the reason is very simple: it's much better to provide an error message (or page) with the same look and feel as the application than such an ugly java stack trace. So besides the exception handlers (for both checked and unchecked exceptions) in the code for expected possible problems, a Pokémon exception handler (for when you just Gotta Catch 'Em All ) is added and when such an exception is caught, a message is shown like "An unexpected error has happened". Mostly some extra information is added so you can contact the customer service with this issue (and 1st line, 2nd line support and/or developers can track it down). I've written such exception handlers myself too, because how well an application is written and tested, there can always pop up an unforeseen situation.
     
    Paul Anilprem
    Enthuware Software Support
    Ranch Hand
    Posts: 3817
    10
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Roel De Nijs wrote:
    Paul Anilprem wrote:When you say "require exception handling", I am assuming that you mean use try/catch blocks. Is that correct?

    A clean and simple yes

    In that case it is quite clear.
    The original question was, "Should you use exception handling when verifying user input?"
    Which resolves to, "Should you use try catch blocks when verifying user input?"

    And the answer should be "too little information to decide". The question is extremely vague.

    Reason: As discussed above, what if user input is null? If there is no check for null, an NPE will be generated in the method and it may either get thrown out of the method or the method may have a null check or wrap the code in a try catch block and process it as per the business rules of the method. Both are perfectly valid courses of actions. Same argument holds for any kind of exception - checked or unchecked. In one case you need not have any try catch blocks and in another, you do need to have them.

     
    Guillermo Ishi
    Ranch Hand
    Posts: 789
    C++ Linux Python
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    In the case of C are these exceptions not thrown by the operating system?

     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Guillermo Ishi wrote:In the case of C are these exceptions not thrown by the operating system?

    From the source code of FileInputStream:So I think it's safe to say, it does (which makes sense, because reading of files is probably operating system dependent)
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Anilprem wrote:And the answer should be "too little information to decide". The question is extremely vague.

    The real exam tells you how many answers are correct. If answers there are borderline correct, choosing the best answer becomes an important skill. If I would face this question on the exam and I had to select two correct answers, I would (without any doubt) select (c) and (d), and proceed to the next question.

    Paul Anilprem wrote:Reason: As discussed above, what if user input is null? If there is no check for null, an NPE will be generated in the method and it may either get thrown out of the method or the method may have a null check or wrap the code in a try catch block and process it as per the business rules of the method. Both are perfectly valid courses of actions.

    I don't agree about both being perfectly valid. And don't get me wrong: they are both valid from the Java compiler's point of view, so both will compile without any compiler error. But from a best practices point of view, only the code providing a null check (and handling a null value gracefully is considered valid (a good approach). If no null check is added and somewhere a try/catch block is added to handle the possible NullPointerException, you are using exceptions as control flow. This is considered to be a bad practice.
     
    Paul Anilprem
    Enthuware Software Support
    Ranch Hand
    Posts: 3817
    10
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Roel De Nijs wrote:
    Paul Anilprem wrote:Reason: As discussed above, what if user input is null? If there is no check for null, an NPE will be generated in the method and it may either get thrown out of the method or the method may have a null check or wrap the code in a try catch block and process it as per the business rules of the method. Both are perfectly valid courses of actions.

    I don't agree about both being perfectly valid. And don't get me wrong: they are both valid from the Java compiler's point of view, so both will compile without any compiler error. But from a best practices point of view, only the code providing a null check (and handling a null value gracefully is considered valid (a good approach). If no null check is added and somewhere a try/catch block is added to handle the possible NullPointerException, you are using exceptions as control flow. This is considered to be a bad practice.


    Totally disagree. I am not talking just from the compilation point of view. There are several Java API that have no null checks and just let the NPE be thrown out. Here is the code for ArrayList's toArray(), just as an example,


    No null check on a. If you call this method with null argument, you will get an NPE, which is generated at a.length. There is no exception handling in this method for null because it makes no sense given the purpose of the method.

    You can find several such methods in the Java API itself. Are you saying all these methods are doing it wrong??
     
    Paul Anilprem
    Enthuware Software Support
    Ranch Hand
    Posts: 3817
    10
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Roel De Nijs wrote:But from a best practices point of view, only the code providing a null check (and handling a null value gracefully is considered valid (a good approach). If no null check is added and somewhere a try/catch block is added to handle the possible NullPointerException, you are using exceptions as control flow. This is considered to be a bad practice.

    I agree with the link you have mentioned. But you are not applying the concept correctly. Not using try/catch doesn't mean you are doing control flow. The most fundamental purpose of a try/catch is to be able to do something special/different in an exceptional situation but only if you have a "plan". What are you going to do if the user input is null? Do you have a plan? Do you want to do something special if the input is null? Then by all means, check for null. If you wrap the user input processing in a try/catch and in the catch for NPE, if you try to do something special, then that would be wrong. That is what the article above is talking about. If you are invoking a method that throws NPE, what is your plan if it does throw NPE? If you don't have any plan, it makes no sense to do anything for that situation. Let it propagate up to the caller.
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Anilprem wrote:You can find several such methods in the Java API itself. Are you saying all these methods are doing it wrong??

    I don't dare to say this (or any other) method is wrong but I would have implemented this method differently. If a null value isn't a valid value to pass in this method as a parameter, my implementation would look like:When you pass the invalid value null to this method, you'll get a much more clear and descriptive error (message) of what's wrong. Tthat's why I prefer my implementation above the current implementation in the Java API. But it seems as of Java 7 a NPE (with or without an appropriate message) is preferred above an IAE (based on the requireNonNull methods of the newly added Objects class). I'm not a huge fan of using NPE for this (that's why I started this thread to find out how others think about it, you made a valuable contribution as well)

    Besides this (little) (personal) optimization I actually don't have any problem with the code of the toArray method. It's completely fine with me. It's all about how this method is invoked if you know the parameter could be null:For me option 2 is an absolute no-go as it is a bad practice.
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Anilprem wrote:If you are invoking a method that throws NPE, what is your plan if it does throw NPE? If you don't have any plan, it makes no sense to do anything for that situation. Let it propagate up to the caller.

    There are no NPEs thrown in our code.

    If I have to invoke the toArray method (mentioned in your previous post), I'll add a null check and will only invoke this method if the array parameter is verified not to be null.
     
    Paul Anilprem
    Enthuware Software Support
    Ranch Hand
    Posts: 3817
    10
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Roel De Nijs wrote:
    Paul Anilprem wrote:You can find several such methods in the Java API itself. Are you saying all these methods are doing it wrong??

    I don't dare to say this (or any other) method is wrong but I would have implemented this method differently. If a null value isn't a valid value to pass in this method as a parameter, my implementation would look like:

    I agree. Do you now realize that as per the meaning of "exception handling" that we established above (i.e. use try catch block), this code doesn't actually do any exception handling? That is my point. The option in the book is too vague precisely because of this reason.
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Anilprem wrote:Do you now realize that as per the meaning of "exception handling" that we established above (i.e. use try catch block), this code doesn't actually do any exception handling? That is my point.

    True! But this code doesn't verify user input either

    If the user has to enter his personal details (an e-mail address, age, salary, date of birth and so on), you need to verify if the entered information is valid. You probably need some exception handling. Although I am perfectly aware that all these verifications can be done without using any exception handling at all Regular expressions are a very powerful feature. For the date of birth you can only validate if its pattern is valid, but not if it's a valid date. You need to use DateFormat.parse which throws a (checked) ParseException if invalid (and thus need exception handling at some time). But you could use the overloaded version which takes a ParsePosition as a 2nd parameter and you'll get null if invalid (no exception handling required).
     
    Paul Anilprem
    Enthuware Software Support
    Ranch Hand
    Posts: 3817
    10
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Roel De Nijs wrote:
    Paul Anilprem wrote:Do you now realize that as per the meaning of "exception handling" that we established above (i.e. use try catch block), this code doesn't actually do any exception handling? That is my point.

    True! But this code doesn't verify user input either

    If the user has to enter his personal details (an e-mail address, age, salary, date of birth and so on), you need to verify if the entered information is valid. You probably need some exception handling. Although I am perfectly aware that all these verifications can be done without using any exception handling at all Regular expressions are a very powerful feature. For the date of birth you can only validate if its pattern is valid, but not if it's a valid date. You need to use DateFormat.parse which throws a (checked) ParseException if invalid (and thus need exception handling at some time). But you could use the overloaded version which takes a ParsePosition as a 2nd parameter and you'll get null if invalid (no exception handling required).


    Excellent! We're almost home

    Now, can you show me an example where you would do exception handling on user input without violating the "flow control using exceptions" rule? Let's say I want to code a method that takes a string input from a user and return the number of times the letter 'a's appears in that given string. How would you code it?
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Anilprem wrote:Let's say I want to code a method that takes a string input from a user and return the number of times the letter 'a's appears in that given string. How would you code it?

    Sure it isn't your homework assignment for this week, Paul? CodeRanch is NotACodeMill

    In Java 7 I would probably write something like this, certainly if I'm not in a loopy mood In Java 8 my code would look like this:Invoking this code is fairly simple:

    I handled a possible null with returning 0. You could also opt to return -1 (or throw an IllegalArgumentException) if the input string is invalid (and you want to distinct from a valid string without the occurence of the letter).
     
    Paul Anilprem
    Enthuware Software Support
    Ranch Hand
    Posts: 3817
    10
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks, Roel! My point is that it is perfectly valid (not just from compilation perspective) to not have any exception handling for a method that verifies user input. That is why I asked you to show any example, where you would use try/catch to "verify user input" without violating the "don't do flow control with exception handling" rule. My point is you cannot. Hence, the answer by OP is actually correct.
     
    Roel De Nijs
    Sheriff
    Posts: 10662
    144
    AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Paul Anilprem wrote:My point is that it is perfectly valid (not just from compilation perspective) to not have any exception handling for a method that verifies user input.

    True!

    If this question would be on the actual exam and I must select just one answer, I'll definitely select option c (accessing data files). But if I have to select 2 answers, I'll select option c (accessing data files) and d (verifying user input), without any doubt. Because from the 5 possible options, those two are outside the programs control and thus are likely (although not required/needed at all) to have exception handling code.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic