Catching exceptions in java

ok, so i am puzzled with catching exceptions… what i wanted to do was restrict the type input when the program starts at the loop of “enter y for temperature
conversion, n to exit.” However, the program enters a continous loop when i enter a letter other than a “y” or “n”. so I don’t understand why it does this and if it is possible to use the catch exception on Strings…


import java.util.Scanner;
 

public class testTemp2
{
	public static void main(String[] args)
	{
		String choice;
		int units;
		temperature t1 = new temperature();
		
		Scanner keyboard = new Scanner(System.in);
		
		boolean exit = false;
		boolean input = false;
			
		while (!exit) {
			System.out.println("Enter 'Y' for temperature conversion, 'N' to exit.");
			while (!input) {
				try {
					choice = keyboard.nextLine();
					input = true;
	
			if (choice.equalsIgnoreCase("y")) 
			{
				System.out.println("enter the temperature.");
				t1.degree = keyboard.nextInt();
				keyboard.nextLine();
				System.out.println("Enter 1 if the degree is in Celsius, Enter 2 if the degree is in Fahrenheit.");
				units = keyboard.nextInt();
				keyboard.nextLine();
			
			switch (units) 
			{
			case 1:
				System.out.println(t1.toString());
				System.out.println("In Fahrenheits, the degree is " + t1.getFahren());
				break;

			case 2:
				System.out.println(t1.toString());
				System.out.println("In Celsius, the degree is " + t1.getCel());
				break;
			default:
				System.out.println("This is not a recognized temperature unit.");
				break;
				}
			}
			else if(choice.equalsIgnoreCase("n")){
			exit = true;
				}
		}
		catch (Exception e) {
					System.out.println("That is not an option. try again.");
					input = false;
				}
		
			}
		}
	}
}

I’m a little confused – what exception are you trying to catch?
I’m not sure why you’re using an exception – something has to throw the exception. It looks like you think the catch block should go off if neither ‘Y’ or ‘N’ is entered (because it falls off the end of the try block?), but that’s not an exception.
More on exceptions here.

You could fix it by explicitly throwing an exception at the end of the try block, but that’s not really what you want to do. Exceptions are for things that go really wrong, you can handle bad input in the code without the try/catch.


if (choice.equalsIgnoreCase("y")) 
{
	    // ... other code ...
}
else if(choice.equalsIgnoreCase("n")){
	    exit = true;
}
else {
	    System.out.println("That is not an option. try again.");
	    input = false;						
}

Your infinite loop is because you complete the try{} block with input=true (there was some input), then the catch{} block is ignore as there’s no exception. Control goes back to the top of the outer loop (exit is still false). But now input is true so the inner loop is skipped, all you get is the println and you’re back at the top of the loop – and stuck doing that forever.

Plus, I’d consider rewriting the logic, so that it’s more

1: Get input
2: Validate input (or goto 1)
3: If ‘Y’ do conversion, goto 1
4: exit

and avoid the nested loop, it’s no real big deal in a simple app like that but I’ve been unraveling nested stuff at work for a while and it’s making me twitchy.

SD

The source of your problem is this:

catch (Exception e)

This line will catch every exception, not just the ones you thought would be thrown. In particular, it will catch NoSuchElementException, which is what Scanner.nextLine() will throw if there is no next line (see the documentation). Since the result of catching an exception is another try at getting a next line, this leads to infinite looping.

Edit: Actually, I’m probably wrong. But it would certainly be elucidating to see what exceptions are actually being caught.

Checked exceptions and try/catch blocks are Evil™. You should only use a try/catch if you really have to, and even then it’s usually better to bubble it up to a top level (like main). Throwing checked exceptions is really only useful in the case where you’re writing a framework/API and want to be sure your end user isn’t doing something incredibly stupid that’s not obvious, or if you’re doing something that can fail AND BE RECOVERED FROM (a lot of people forget this, there’s usually no point continuing in your 100% graphical application if it’s impossible to get a display mode, so there’s no point forcing the programmer to check it – they can still do a try-catch manually if they want to do cleanup/error handling) for tons of little semi-uncontrollable reasons (i.e. file i/o).

The correct way to do things is to make sure that exceptions can’t be thrown by your code, it makes the program much easier to read and it’s usually easier to prevent a problem than to fix the mess it causes after it happens.

Remember Evil™ doesn’t mean “never use it,” it means “think really hard and have a damn good reason.”

As said above, the infinite loop is coming from catching all exceptions rather than specifying, the two ways to fix this is to change the exception in the catch check, in which case your program will just crash unless you find another way to handle it, or to add “if keyboard.hasNext().”

ugh… what a pain… okay, so what i gather from the comments here is that the second loop i have is unnecessary and that it is better not to have the try/catch block, not to mention i am not catching anything…

unfortunately, i want to use the catch exception coding and thus i have to go through this painful process… There were two parts to the code i needed: one was to add an error check to the option menu. This is part where i ask the user if they want to try a temperature conversion or exit the program. At this point, i am trying to ensure the user enters either a “Y” or “N”… anything else, i want to display the “this is not an option, try again” message. I attempting to make this first part work…

The second part of the coding i have not worked on yet is that if the user selects “Y”, i want to ensure that they enter the correct input for temperature setting and the temperature to be converted…Otherwise i display an error message and allow the user to re-enter the information again…


public class temperature implements TemperatureInterface
{
	public double degree, cel, fahren;
	public int units;
	
	public temperature()
	{
	}
	public double getCel()
	{
		cel = (degree - 32) * 5/9;
		return cel;
	}
	public double getFahren()
	{
		fahren = (degree * 9)/5 + 32;
		return fahren;
	}
	public String toString()
	{
		String temp = "You have entered " + degree + " " + units;
		return temp;
		
	}
}