Error handling

To deal with invalid data

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 1712 Views - Last Post: 10 April 2007 - 01:10 PM Rate Topic: -----

#1 stew_downunder  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 04-April 07

Error handling

Posted 04 April 2007 - 02:08 AM

Hi people!

This is my first post and I'm a newly enrolled student/novice to Java.

I have created a simple program that calculates the area of a box, and the error handling I have obviously got wrong. When I run the program, it asks the first question ("Enter the height of the box") and then handles the error ok when invalid data entered, THEN when asked the second question ("Enter the width of the box") it handles the error BUT then takes you all the way back to the first question instead of returning to the second.

Can someone please help out here as I'm sure it would be a simple fix.
I have posted the code below.

Thanks - Stew.


import java.io.*;
 
public class TestProg
{
	public static void main(String args []) throws IOException
	{
		String strHeight, strWidth;
		float height, width, total;
		boolean done = false;
		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
 
		while(!done)
		{
			try
			{
				System.out.print("Enter the height of the box: ");
				strHeight = dataIn.readLine();
				height = Float.parseFloat(strHeight);
				System.out.println();
				if(height <= 0) throw new NumberFormatException();
 
				System.out.print("Enter the width of the box: ");
				strWidth = dataIn.readLine();
				width = Float.parseFloat(strWidth);
				System.out.println();
				if(width <= 0) throw new NumberFormatException();
				else done = true;
 
				total = height * width;
 
				System.out.println("The area = " + total);
			}
			catch(NumberFormatException e)
			{
				System.out.println("Invalid format!");
			}
		}
	}
}


Is This A Good Question/Topic? 0
  • +

Replies To: Error handling

#2 Ryan Smith  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 14-February 07

Re: Error handling

Posted 04 April 2007 - 04:57 AM

Someone could explain to me why it works when I use println() but not print() to output the directions....


But I had someone more success with this code:


import java.io.*;

public class test
{
	public static void main(String args [])
	{
		String strHeight, strWidth;
		float height, width, total;
		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

		while(true)
		{
			//for some reason this does not work if it is print("......");
		System.out.println("Enter the height of the box: ");
		try {
		strHeight = dataIn.readLine();
			   height = Float.parseFloat(strHeight);
		if(height <= 0) throw new NumberFormatException();
		} catch (Exception e) {
		System.err.println("Invalid format");
		continue;
		}
			//for some reason this does not work if it is print("......");
		System.out.println("Enter the width of the box: ");
		try {
		strWidth = dataIn.readLine();
		width = Float.parseFloat(strWidth);
		if(width <= 0) throw new NumberFormatException();
		} catch (Exception e) {
		System.err.println("Invalid format");
		continue;
		}
				total = height * width;
				System.out.println("The area = " + total);
		break;
		}
	}
}



I hate it when Java does not obey me!
I had some difficulty with the print() you used.

I took the liberty of rewriting your code block, but it's essentially the same. The try/catch could be combined.
I migrated it to an infinite while loop, saving the definition of a variable. You can use continue/break to work with it.

Personal preference though. =P

Unless you need to use Standard Input, JOptionPane is a much easier way to retrieve generic input.

String input = JOptionPane.showInputDialog("You type the question here");

just include javax.swing.JOptionPane;
Was This Post Helpful? 0
  • +
  • -

#3 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Error handling

Posted 04 April 2007 - 10:08 AM

View Poststew_downunder, on 4 Apr, 2007 - 02:08 AM, said:

Hi people!

This is my first post and I'm a newly enrolled student/novice to Java.

I have created a simple program that calculates the area of a box, and the error handling I have obviously got wrong. When I run the program, it asks the first question ("Enter the height of the box") and then handles the error ok when invalid data entered, THEN when asked the second question ("Enter the width of the box") it handles the error BUT then takes you all the way back to the first question instead of returning to the second.

Can someone please help out here as I'm sure it would be a simple fix.
I have posted the code below.

Thanks - Stew.


import java.io.*;
 
public class TestProg
{
	public static void main(String args []) throws IOException
	{
		String strHeight, strWidth;
		float height, width, total;
		boolean done = false;
		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
 
		while(!done)
		{
			try
			{
				System.out.print("Enter the height of the box: ");
				strHeight = dataIn.readLine();
				height = Float.parseFloat(strHeight);
				System.out.println();
				if(height <= 0) throw new NumberFormatException();
 
				System.out.print("Enter the width of the box: ");
				strWidth = dataIn.readLine();
				width = Float.parseFloat(strWidth);
				System.out.println();
				if(width <= 0) throw new NumberFormatException();
				else done = true;
 
				total = height * width;
 
				System.out.println("The area = " + total);
			}
			catch(NumberFormatException e)
			{
				System.out.println("Invalid format!");
			}
		}
	}
}


The reason it's repeating the frist question is because you have everything within one while statement. So, if either of them causes an exception and the done variable is not set to true, the loop will continue at the top, which is where your first question is. There are lots of ways to do what you are trying to do. The simple approach would be to have a loop with separate flags for each question. Another approach might have an 2 x n array with each row having a question and a variable representing the response. Each time you get a response that does not generate an exception, you can increment some global integer counter that will access the next question/variable in the array. Once you reach the end of the array you can set the done flag. Yet another possibility would be to have an array pf QuestionResponse (just made that up) objects instead of a 2 x n array. Hope that helps.

This post has been edited by alcdotcom: 04 April 2007 - 10:10 AM

Was This Post Helpful? 0
  • +
  • -

#4 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Error handling

Posted 04 April 2007 - 10:36 AM

Many say that you should avoid using break and continue. I thin it's up to each person to decide, but here are some interesting points on the matter:
http://www.javaranch...eLong.jsp#avoid

Having written programs in C/C++ and unix shells, I have experience with break and continue. I prefer to stick to a structured approach that has one entry and one exit for each structure. It sometimes creates complex nested structures, but I find that if I think about it, I can find ways to avoid that. Just some food for thought.
Was This Post Helpful? 0
  • +
  • -

#5 stew_downunder  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 04-April 07

Re: Error handling

Posted 04 April 2007 - 10:13 PM

Thank you both for the help - I will try those methods out suggested - I like the array idea, and yes I can now see that I should not have used just the one while loop - much appreciated.
Was This Post Helpful? 0
  • +
  • -

#6 stew_downunder  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 04-April 07

Re: Error handling

Posted 09 April 2007 - 04:11 AM

Well, I have tried to modify my code by adding flags for each question and now it won't compile.

It gives me the following error messages:

java:17: variable height might not have been initialized
if(height <= 0) throw new NumberFormatException ();

java:34: variable width might not have been initialized
if(width <= 0) throw new NumberFormatException ();

java:47: variable height might not have been initialized
total = height * width;

java:47: variable width might not have been initialized
total = height * width;


Below is the modified code:

import java.io.*;

public class CalculateBox
{
	public static void main(String args []) throws IOException
	{
		String strHeight, strWidth;
		float height, width, total;
		boolean heightDone = false;
		boolean widthDone = false;
		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

		while(!heightDone)
		{
			try
			{
				if(height <= 0) throw new NumberFormatException ();
				else heightDone = true;
				System.out.print("Enter the height of the box: ");
				strHeight = dataIn.readLine();
				height = Float.parseFloat(strHeight);
			}

			catch(NumberFormatException e)
			{
				System.out.println("Invalid height entry! - Try again");
			}
		}

		while(!widthDone)
		{
			try
			{
				if(width <= 0) throw new NumberFormatException ();
				else widthDone = true;
				System.out.print("Enter the width of the box: ");
				strWidth = dataIn.readLine();
				width = Float.parseFloat(strWidth);
			}

			catch(NumberFormatException e)
			{
				System.out.println("Invalid width entry! - Try again:");
			}
		}

		total = height * width;

		System.out.println("The area = " + total);
	}
}

Was This Post Helpful? 0
  • +
  • -

#7 Ryan Smith  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 14-February 07

Re: Error handling

Posted 09 April 2007 - 07:55 AM

You can't count on a try/catch block to assign values to a variable. If there is an exception, the assignments before the exception will take, but not the assignments after. In this case there is no error, but the Java compiler is warning you that if there is an exception, some variables could remain undefined.

The easiest way to correct this would be to assign an insignificant value to them when they are declared.

Such as:


	   String strHeight = "0", strWidth = "0";
		float height = 0, width = 0, total = 0;




Then if there is an exception, your program will still be able to handle the variables... but because they are 0, there won't be any error output.

(I'm still wondering why System.out.print("ASKJDALSJD") is delayed, but System.out.println("stringstuff") will work)
If you leave it as System.out.print("stuff"); it appears that the program is waiting for input before it displays the "enter data" string.
That's corrected by changing to System.out.println("anotherstring"); Does anyone else have this problem? Or is it just me?

I had to change your print() to println().... and I also had to move your exception checking statement to the end of the loops....

From This:
try
			{
				if(height <= 0) throw new NumberFormatException ();
					 else heightDone = true;
				System.out.print("Enter the height of the box: ");
				strHeight = dataIn.readLine();
				height = Float.parseFloat(strHeight);
		
			}
//////////////////////////////////////
try
			{
				if(width <= 0) throw new NumberFormatException ();
					 else widthDone = true;
				System.out.print("Enter the width of the box: ");
				strWidth = dataIn.readLine();
				width = Float.parseFloat(strWidth);
		
			}



To This:
try
			{
				System.out.println("Enter the height of the box: ");
				strHeight = dataIn.readLine();
				height = Float.parseFloat(strHeight);
				if(height <= 0) throw new NumberFormatException ();
					 else heightDone = true;
			}
////////////////////////////////////////
try
			{
				System.out.println("Enter the width of the box: ");
				strWidth = dataIn.readLine();
				width = Float.parseFloat(strWidth);
				if(width <= 0) throw new NumberFormatException ();
					 else widthDone = true;
			}



But I ran it and it seems to function the way it should.

Here it is in full:

import java.io.*;

public class CalculateBox
{
	public static void main(String args []) throws IOException
	{
		String strHeight = "0", strWidth = "0";
		float height = 0, width = 0, total = 0;
		boolean heightDone = false;
		boolean widthDone = false;
		BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));

		while(!heightDone)
		{
			try
			{
				System.out.println("Enter the height of the box: ");
				strHeight = dataIn.readLine();
				height = Float.parseFloat(strHeight);
				if(height <= 0) throw new NumberFormatException ();
					 else heightDone = true;
			}

			catch(NumberFormatException e)
			{
				System.out.println("Invalid height entry! - Try again");
			}
		}

		while(!widthDone)
		{
			try
			{
				System.out.println("Enter the width of the box: ");
				strWidth = dataIn.readLine();
				width = Float.parseFloat(strWidth);
				if(width <= 0) throw new NumberFormatException ();
					 else widthDone = true;
			}

			catch(NumberFormatException e)
			{
				System.out.println("Invalid width entry! - Try again:");
			}
		}

		total = height * width;

		System.out.println("The area = " + total);
	}
}



If that doesn't do it.... surely post again.
Was This Post Helpful? 0
  • +
  • -

#8 Ryan Smith  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 14-February 07

Re: Error handling

Posted 09 April 2007 - 08:08 AM

stew_downunder This post is not in reply to your topic. Don't worry about it.

View Postalcdotcom, on 4 Apr, 2007 - 10:36 AM, said:

Many say that you should avoid using break and continue. I thin it's up to each person to decide, but here are some interesting points on the matter:
http://www.javaranch...eLong.jsp#avoid

Having written programs in C/C++ and unix shells, I have experience with break and continue. I prefer to stick to a structured approach that has one entry and one exit for each structure. It sometimes creates complex nested structures, but I find that if I think about it, I can find ways to avoid that. Just some food for thought.



I find break and continue incredibly useful... I disagree with most of the items on the JavaRanch formatting guide, with the exception of some of the formatting.

You've got an array of people, but some are null. You need to print the names of the ones that exist, and then do additional stuff to their object.
I like this:
for(int i = 0; i < arrayLength; i++) {
	 if(array[i] == null)
		  continue;
	 System.out.println("Person " + i + " is named " + array[i].getName() );
	 //blahblahblah do other stuff to object array[i]
	 array[i].kill();
	 array[i] = null;
}



better than
for(int i = 0; i < arrayLength; i++) {
	 if(array[i] != null)
	 {
		  System.out.println("Person " + i + " is named " + array[i].getName() );
		  //blahblahblah do other stuff to object array[i]
		  array[i].kill();
		  array[i] = null;
	 }
}



I just think the use of continue makes that easier to read.... at least for me.
Was This Post Helpful? 0
  • +
  • -

#9 stew_downunder  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 04-April 07

Re: Error handling

Posted 09 April 2007 - 07:36 PM

Fantastic Ryan - many thanks!!

All working good and well.
Was This Post Helpful? 0
  • +
  • -

#10 Ryan Smith  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 14-February 07

Re: Error handling

Posted 09 April 2007 - 10:01 PM

Thank the forum! That's what it's here for!

It's been a great help to me a many times.

=D
Was This Post Helpful? 0
  • +
  • -

#11 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Error handling

Posted 10 April 2007 - 03:12 AM

View PostRyan Smith, on 9 Apr, 2007 - 08:08 AM, said:

I find break and continue incredibly useful... I disagree with most of the items on the JavaRanch formatting guide, with the exception of some of the formatting.

You've got an array of people, but some are null. You need to print the names of the ones that exist, and then do additional stuff to their object.
I like this:
for(int i = 0; i < arrayLength; i++) {
	 if(array[i] == null)
		  continue;
	 System.out.println("Person " + i + " is named " + array[i].getName() );
	 //blahblahblah do other stuff to object array[i]
	 array[i].kill();
	 array[i] = null;
}



better than
for(int i = 0; i < arrayLength; i++) {
	 if(array[i] != null)
	 {
		  System.out.println("Person " + i + " is named " + array[i].getName() );
		  //blahblahblah do other stuff to object array[i]
		  array[i].kill();
		  array[i] = null;
	 }
}



I just think the use of continue makes that easier to read.... at least for me.


To each his own. I find the second one more readable. I used break and continue when I wrote shell scripts or C programs, as a unix admin. But I found that, the larger my scripts/programs became, the better it was to have a single exit point for functions. Otherwise, can be confusing for people to read. Continue is not nearly as bad, but in my experience, people tend to visually lose the structure of a loop when it's full of continues instead broken up into decision blocks. Having had years of experience, I can look at either with no problem, but how often are veteran guys reading my old code? Not much. It's usually the new guy, fresh from the university, who is tasked with looking at, getting up to speed with, and debugging existing code. And I can tell you that, on the whole, break, labeled break, continue, and goto are not being taught - mostly because they are not compatible with structured programming.
Was This Post Helpful? 0
  • +
  • -

#12 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: Error handling

Posted 10 April 2007 - 04:11 AM

I must say that it depends on the company you are working for. Generally there are two main types:
1) it hires a lot of people, and doesn't care about their training and (quality of) skills that much
2) it will try to hand-pick the best, who they don't have to babysit all day, and 1 can do the work of 2 or 3 from the first group
Both of these attitudes work, but in different circumstances. Big companies tend to use #1(Microsoft), while smaller ones the second( Fog Creek - the guy has a really good blog on software development called Joel on software).
I'd like to believe that approach #2 is better, and programmers should not care about using advanced constructs in their code in fear of some novice, half-trained guy having problems with it - I don't consider someone who doesn't know continue a fully trained programmer, but I agree that goto should be banned. So I would say that I wouldn't be happy if I had to use the Java Ranch rules. Sun's official Java style guide is really useful on the other hand, and mostly enough.
Btw what I've found the most amateurish advice in the JR article is the identation: today you can configure in every IDE (vi included) the identation you prefer, so setting strict rules for that seems just plain superfluous, when you can reformat the code exactly to your liking in a jiffy- and not 2 people are the same, so one thing that fits someone makes the other go mad. (Anyway, good practice is really useful there, so recommendations are always welcomed...)
Ahh, sorry, it is geting way offtopic, should be continued in Software development....
Was This Post Helpful? 0
  • +
  • -

#13 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,833
  • Joined: 02-January 06

Re: Error handling

Posted 10 April 2007 - 07:52 AM

View Post1lacca, on 10 Apr, 2007 - 04:11 AM, said:

I must say that it depends on the company you are working for. Generally there are two main types:
1) it hires a lot of people, and doesn't care about their training and (quality of) skills that much
2) it will try to hand-pick the best, who they don't have to babysit all day, and 1 can do the work of 2 or 3 from the first group
Both of these attitudes work, but in different circumstances. Big companies tend to use #1(Microsoft), while smaller ones the second( Fog Creek - the guy has a really good blog on software development called Joel on software).
I'd like to believe that approach #2 is better, and programmers should not care about using advanced constructs in their code in fear of some novice, half-trained guy having problems with it - I don't consider someone who doesn't know continue a fully trained programmer, but I agree that goto should be banned.

I read Joel on Software. Good blog. In a perfect world you could code how you want and not have to worry about people reading your code. But in the real world you do have to deal with this. Whether you consider them fully-trained or not, there are probably plenty of people graduating without any real knowledge of continue or break, outside of the context of switch statements. In general, I would say many people graduating from college are not "fully trained." I had an advanced Java class with a second year grad student that couldn't program her way out of a wet paper bag. Before I'd consider anyone fully trained, I'd want to see that they'd worked in the industry and done some development in a production environment using enterprise tools and know how to program well. That's how I'd measure it and not whether or not they know every keyword or have a certification. That means nothing to me. You interview with me, you'd better be prepared to code. :)

View Post1lacca, on 10 Apr, 2007 - 04:11 AM, said:

Btw what I've found the most amateurish advice in the JR article is the identation: today you can configure in every IDE (vi included) the identation you prefer, so setting strict rules for that seems just plain superfluous, when you can reformat the code exactly to your liking in a jiffy- and not 2 people are the same, so one thing that fits someone makes the other go mad. (Anyway, good practice is really useful there, so recommendations are always welcomed...)
Ahh, sorry, it is geting way offtopic, should be continued in Software development....


I don't agree with everything said in the JR article. In fact, I haven't even read their entire guide as it's meant more for novices, I think. I was just pointing out the specific bits about the flow-control keywords.
Was This Post Helpful? 0
  • +
  • -

#14 Ryan Smith  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 14-February 07

Re: Error handling

Posted 10 April 2007 - 08:19 AM

I agree, a programmer isn't really fully trained without knowing how to properly use break and continue.
I also agree, goto: should be banned. Not only can it get ridiculously confusing... it's reminiscent of batch files, and its usefulness stops there.

break, continue... according to JR may hinder breaking things into smaller calls, but some things.... a breakup may not be intended or even necessary.

The only formatting that I agree with is that you stick to one. As long as you maintain your formatting, I don't care if your methods look like

public void aMethod() {
}



or
public void aMethod()
{
}



as long as you have continuity.

It may not be the best programming practice, but the more readable and described your code is, the easier it is to find someone to replace you. There was a kid in one of my Java classes who used variables such as h9d8s7a6. Really. No comments. And methods named things like m3j3j3j3(). His coding's cryptic.
Was This Post Helpful? 0
  • +
  • -

#15 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: Error handling

Posted 10 April 2007 - 09:04 AM

Quote

I'd consider anyone fully trained, I'd want to see that they'd worked in the industry and done some development in a production environment using enterprise tools and know how to program well. That's how I'd measure it and not whether or not they know every keyword or have a certification. That means nothing to me. You interview with me, you'd better be prepared to code. smile.gif

Agreed, on hands experience is essential - ok, I haven't pointed out, but never denied it either. And yes, I know quite a number of students who graduated without any real programming skills. However my main point was (and seems to be missed) that in some environments you can code without thinking about babysitting somebody who comes after you, because the HR will make sure, that (s)he won't even see your office from the inside, and you can concentrate on writing good code productively. I think it is much more important to have each function be just as big as to fit onto one, or one and a half screen (ok, without going into obfuscation, naturally) than to make it a never ending story, because it is easier to look at at once. Anyway, it is all about tastes, but it is also true, that in some places you do have to produce code that can be read and easily modified by beginners, or droids, or whatever...
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2