Exception handling help (newbie)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DHS1
    New Member
    • Dec 2008
    • 3

    Exception handling help (newbie)

    Hey guys. I have a lab that is due in two weeks, but I wanted to start on it now. Problem is, I'm at home during christmas break so I can't ask my professors. Here's my problem:

    I am given a very fragile program and I have to add the exception handling and error checking and pretty much make it uncrashable.

    I will show just one small step in this lab. If you can answer it, I think I'll be able to do the rest. I just need to get headed in the right direction because my Java book and online tutorials aren't helping.

    I need to do what the TODO says. This is a Constructor method. The length it's talking about has to be 10. Here's the code:

    Code:
    	public DateStringConverter(String startDate, String endDate ){
    //TODO make sure that both text fields contain text; generate an Exception if NULL strings or invalid length;
    //TODO In the Exception, specify the reason: exactly which field (Start or End Date) contained the error.
    		
    		parseDateStrings( startDate, endDate );
    	}
    I'm then supposed to catch the exceptions (that I made in that constructor) in this code (remember Im just showing a small secion)

    Code:
    // prompt for input
    		String startDate = JOptionPane.showInputDialog("Enter a start date as mm/dd/yyyy.");
    		String endDate = JOptionPane.showInputDialog("Enter an end date as mm/dd/yyyy");
    
    		//TODO catch Exceptions thrown from within DateStringConverter; report errors on exceptions,
    		//TODO report EXACTLY the cause of the error in a message dialog, and loop to repeat the previous prompts
    		DateStringConverter dsc = new DateStringConverter(startDate, endDate);
    I tried putting exception handling in the constructor method I showed you earlier, and this is what it looked like:

    Code:
    	public DateStringConverter(String startDate, String endDate ) throws Exception{
    //TODO make sure that both text fields contain text; generate an Exception if NULL strings or invalid length;
    //TODO In the Exception, specify the reason: exactly which field (Start or End Date) contained the error.
    		if((startDate==null)||(startDate.length()>10||startDate.length()<10)){
    			Exception start = new Exception("If start date is null or too short/long");
    			throw start;
    		}
    		if((endDate==null)||(endDate.length()>10||endDate.length()<10)){
    			Exception end = new Exception("If end date is null or too short/long");
    			throw end;
    		}
    		parseDateStrings( startDate, endDate );
    But when I went to the main method (second block of code I showed you) I couldn't figure out how to catch the exception named "start" that I threw.

    So can anyone tell me how I could do this? The TODO:'s in the code are what I need to do in case you didn't read this whole thing. Thanks, and let me know if you need to see more of the code.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Java already has an exception for exactly this purpose: the IllegalArgument Exception. It is an unchecked exception so you can throw it whenever appropriate without declaring a 'throws' clause in the method headers.

    One little method that checks the validity of the argument(s) can do the job:

    Code:
    private void checkArgument(String date, String prompt) {
       if (date == null) 
          throw new IllegalArgumentException(prompt+" is null");
       if (date.length() != 10)
          throw new IllegalArgumentException(prompt+" has wrong length");
    }
    Call that method whereever needed and catch the IAE whereever needed.

    kind regards,

    Jos

    Comment

    • DHS1
      New Member
      • Dec 2008
      • 3

      #3
      Originally posted by JosAH
      Java already has an exception for exactly this purpose: the IllegalArgument Exception. It is an unchecked exception so you can throw it whenever appropriate without declaring a 'throws' clause in the method headers.

      One little method that checks the validity of the argument(s) can do the job:

      Code:
      private void checkArgument(String date, String prompt) {
         if (date == null) 
            throw new IllegalArgumentException(prompt+" is null");
         if (date.length() != 10)
            throw new IllegalArgumentException(prompt+" has wrong length");
      }
      Call that method whereever needed and catch the IAE whereever needed.

      kind regards,

      Jos
      Ok thanks. How would I specify the IAE for each separate problem? I mean, how can I catch one, and say it was because the string was null, and catch the other and say that it was because the string was the wrong length? Because if I do:

      catch(IllegalAr gumentException e) then i can't tell which problem made it throw the IAE. I need to tell the user whether they entered a null string, or a string of wrong length. and I need to know just by the exception thrown (I'm not allowed to send messages from inside the method, only allowed to send them from the main method that I call this method in.

      Here is what I mean:

      method:
      Code:
      public DateStringConverter(String startDate, String endDate ){
      //TODO make sure that both text fields contain text; generate an Exception if NULL strings or invalid length;
      //TODO In the Exception, specify the reason: exactly which field (Start or End Date) contained the error.
      		if((startDate==null)||(startDate.length()>10||startDate.length()<10)){
      			throw new IllegalArgumentException(startDate+"is null or wrong length");
      		}
      		if((endDate==null)||(endDate.length()>10||endDate.length()<10)){
      			throw new IllegalArgumentException(endDate + "is null or wrong length");
      		}
      		parseDateStrings( startDate, endDate );
      	}
      and then I catch it in this main method (this is part of the main methods code)

      Code:
      int ok = -1;
      		while(ok==-1){
      			try {
      				dsc = new DateStringConverter(startDate, endDate);
      				ok = 1;
      				}
      			catch(IllegalArgumentException e){
      				startDate = JOptionPane.showInputDialog("Exception caught. Your string was null or the wrong length. Enter a start date as mm/dd/yyyy.");
      				endDate = JOptionPane.showInputDialog("Exception caught. Your string was null or the wrong length. Enter an end date as mm/dd/yyyy");
      			}
      		}
      but with this I can't specify whether the problem was in the startDate or the endDate?

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by DHS1
        Ok thanks. How would I specify the IAE for each separate problem? I mean, how can I catch one, and say it was because the string was null, and catch the other and say that it was because the string was the wrong length? Because if I do:

        catch(IllegalAr gumentException e) then i can't tell which problem made it throw the IAE. I need to tell the user whether they entered a null string, or a string of wrong length. and I need to know just by the exception thrown (I'm not allowed to send messages from inside the method, only allowed to send them from the main method that I call this method in.
        As I suggested the error is in the message of the exception (read the API documentation) but of course you can define your own exceptions that both extend the IAE, say the NullArgumentExc eption and the WrongLengthExce ption. They won't really need a message then. Note that there already exists a NullPointerExce ption.

        kind regards,

        Jos

        Comment

        • DHS1
          New Member
          • Dec 2008
          • 3

          #5
          Originally posted by JosAH
          As I suggested the error is in the message of the exception (read the API documentation) but of course you can define your own exceptions that both extend the IAE, say the NullArgumentExc eption and the WrongLengthExce ption. They won't really need a message then. Note that there already exists a NullPointerExce ption.

          kind regards,

          Jos
          Ohh I finally see what you're saying. I should use the .getMessage() method to verify exactly which NumberFormatExc eption it threw.

          This is what I did and it works great. But is there a simpler way, or an alternative way you know of?

          Code:
          	public DateStringConverter(String startDate, String endDate ){
          		if((startDate==null)||(startDate.length()>10||startDate.length()<10)){
          			throw new NumberFormatException("startDate");
          		}
          		if((endDate==null)||(endDate.length()>10||endDate.length()<10)){
          			throw new NumberFormatException("endDate");
          		}
          		parseDateStrings( startDate, endDate );
          Code:
          DateStringConverter dsc = null;
          		byte ok = 1;
          		while(ok==1){
          			try {
          				dsc = new DateStringConverter(startDate, endDate);
          				ok = 0;
          			}
          			catch(NumberFormatException e){
          				if(e.getMessage()=="startDate"){
          					startDate = JOptionPane.showInputDialog("NumberFormatException caught in START DATE. Your date contained non-numbers, wrong date format, or tried to exit. Enter a start date as mm/dd/yyyy.");
          				}
          				if(e.getMessage()=="endDate"){
          					endDate = JOptionPane.showInputDialog("NumberFormatException caught in END DATE. Your date contained non-numbers, wrong date format, or tried to exit. Enter an end date as mm/dd/yyyy.");
          				}
          			}
          		}
          Thank you sooooooo much by the way. This was making me rage for a good 2 days.

          Comment

          Working...