473,324 Members | 2,166 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Exception handling help (newbie)

3
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:

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

Expand|Select|Wrap|Line Numbers
  1. // prompt for input
  2.         String startDate = JOptionPane.showInputDialog("Enter a start date as mm/dd/yyyy.");
  3.         String endDate = JOptionPane.showInputDialog("Enter an end date as mm/dd/yyyy");
  4.  
  5.         //TODO catch Exceptions thrown from within DateStringConverter; report errors on exceptions,
  6.         //TODO report EXACTLY the cause of the error in a message dialog, and loop to repeat the previous prompts
  7.         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:

Expand|Select|Wrap|Line Numbers
  1.     public DateStringConverter(String startDate, String endDate ) throws Exception{
  2. //TODO make sure that both text fields contain text; generate an Exception if NULL strings or invalid length;
  3. //TODO In the Exception, specify the reason: exactly which field (Start or End Date) contained the error.
  4.         if((startDate==null)||(startDate.length()>10||startDate.length()<10)){
  5.             Exception start = new Exception("If start date is null or too short/long");
  6.             throw start;
  7.         }
  8.         if((endDate==null)||(endDate.length()>10||endDate.length()<10)){
  9.             Exception end = new Exception("If end date is null or too short/long");
  10.             throw end;
  11.         }
  12.         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.
Dec 28 '08 #1
4 1760
JosAH
11,448 Expert 8TB
Java already has an exception for exactly this purpose: the IllegalArgumentException. 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:

Expand|Select|Wrap|Line Numbers
  1. private void checkArgument(String date, String prompt) {
  2.    if (date == null) 
  3.       throw new IllegalArgumentException(prompt+" is null");
  4.    if (date.length() != 10)
  5.       throw new IllegalArgumentException(prompt+" has wrong length");
  6. }
  7.  
Call that method whereever needed and catch the IAE whereever needed.

kind regards,

Jos
Dec 28 '08 #2
DHS1
3
@JosAH
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(IllegalArgumentException 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:
Expand|Select|Wrap|Line Numbers
  1. public DateStringConverter(String startDate, String endDate ){
  2. //TODO make sure that both text fields contain text; generate an Exception if NULL strings or invalid length;
  3. //TODO In the Exception, specify the reason: exactly which field (Start or End Date) contained the error.
  4.         if((startDate==null)||(startDate.length()>10||startDate.length()<10)){
  5.             throw new IllegalArgumentException(startDate+"is null or wrong length");
  6.         }
  7.         if((endDate==null)||(endDate.length()>10||endDate.length()<10)){
  8.             throw new IllegalArgumentException(endDate + "is null or wrong length");
  9.         }
  10.         parseDateStrings( startDate, endDate );
  11.     }
and then I catch it in this main method (this is part of the main methods code)

Expand|Select|Wrap|Line Numbers
  1. int ok = -1;
  2.         while(ok==-1){
  3.             try {
  4.                 dsc = new DateStringConverter(startDate, endDate);
  5.                 ok = 1;
  6.                 }
  7.             catch(IllegalArgumentException e){
  8.                 startDate = JOptionPane.showInputDialog("Exception caught. Your string was null or the wrong length. Enter a start date as mm/dd/yyyy.");
  9.                 endDate = JOptionPane.showInputDialog("Exception caught. Your string was null or the wrong length. Enter an end date as mm/dd/yyyy");
  10.             }
  11.         }
but with this I can't specify whether the problem was in the startDate or the endDate?
Dec 28 '08 #3
JosAH
11,448 Expert 8TB
@DHS1
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 NullArgumentException and the WrongLengthException. They won't really need a message then. Note that there already exists a NullPointerException.

kind regards,

Jos
Dec 28 '08 #4
DHS1
3
@JosAH
Ohh I finally see what you're saying. I should use the .getMessage() method to verify exactly which NumberFormatException it threw.

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

Expand|Select|Wrap|Line Numbers
  1.     public DateStringConverter(String startDate, String endDate ){
  2.         if((startDate==null)||(startDate.length()>10||startDate.length()<10)){
  3.             throw new NumberFormatException("startDate");
  4.         }
  5.         if((endDate==null)||(endDate.length()>10||endDate.length()<10)){
  6.             throw new NumberFormatException("endDate");
  7.         }
  8.         parseDateStrings( startDate, endDate );
Expand|Select|Wrap|Line Numbers
  1. DateStringConverter dsc = null;
  2.         byte ok = 1;
  3.         while(ok==1){
  4.             try {
  5.                 dsc = new DateStringConverter(startDate, endDate);
  6.                 ok = 0;
  7.             }
  8.             catch(NumberFormatException e){
  9.                 if(e.getMessage()=="startDate"){
  10.                     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.");
  11.                 }
  12.                 if(e.getMessage()=="endDate"){
  13.                     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.");
  14.                 }
  15.             }
  16.         }
Thank you sooooooo much by the way. This was making me rage for a good 2 days.
Dec 28 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Babu | last post by:
Hi, I am a Perl newbie and have a doubt on Perl exception handling. My understanding regarding exception handling is execute a piece of code, if any exception occurs, handle the exception and...
11
by: adi | last post by:
Dear all, This is more like a theoretical or conceptual question: which is better, using exception or return code for a .NET component? I had created a COM object (using VB6), which uses...
7
by: Noor | last post by:
please tell the technique of centralize exception handling without try catch blocks in c#.
3
by: Master of C++ | last post by:
Hi, I am an absolute newbie to Exception Handling, and I am trying to retrofit exception handling to a LOT of C++ code that I've written earlier. I am just looking for a bare-bones, low-tech...
2
by: tom | last post by:
Hi, I am developing a WinForm application and I am looking for a guide on where to place Exception Handling. My application is designed into three tiers UI, Business Objects, and Data Access...
9
by: C# Learner | last post by:
Some time ago, I remember reading a discussion about the strengths and weaknesses of exception handling. One of the weaknesses that was put forward was that exception handling is inefficient (in...
44
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level...
3
by: Mr Newbie | last post by:
When you write code, you can generally structure it so that you handle all the errors, so when is it most appropriate to Throw an exception rather than coding for error handling in a more granular...
1
by: George2 | last post by:
Hello everyone, Such code segment is used to check whether function call or exception- handling mechanism runs out of memory first (written by Bjarne), void perverted() { try{
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.