简体   繁体   中英

Exceptions in Java - Try/ Catch

I'm learning Java and I have this program that tells the sign depending on the day and month the user writes. The program works as it is, but if the user enters a day like 90 or so, the program doesnt evaluate that "error". Can I correct this with a try/catch? If so, how do I write it? Here's the code (a piece of it), thanks in advance

  import java.util.Scanner;
    public class Signo{
        public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int day, month;


        System.out.println("Day Input:");

        day=in.nextInt();

        System.out.println("Month Input:");

        month=in.nextInt();

           int result=getSign(day,month);

        }

    private static int getSign(int day, int month){

        switch(month){
                    case 1:
        if(month==1 && day>=20){
            System.out.println("Your sign is Aquarius");
            }else{
            System.out.println("Your sign is Capricorn");
        }
                break;
        //etc
      }
        return day;
    }
    }

There is actually no error. You are asking for an integer and the user is providing just that. It is up to you to verify if it is a valid number for your current logic. I would also re-write your getSign() method, there is really no point in mixing a switch and an if. Not at least in your case.

I would do something like this:

day=in.nextInt();
if(day > 30) {
    while(day > 30) {
        // Number is too high, feel free to spit this message out
        day=in.nextInt();
    }

Or even better:

while(day > 30) {
    day=in.nextInt();
}

You could also extract your day = in.nextInt(); to a single method and return a boolean if it is valid/invalid

It's pretty simple, really...

try
{
     //statements that may cause an exception
}
catch (exception(type) e(object))‏
{
     //error handling code
}

That's all you really need right there. Just put your code that you think might break in the appropriate spot.

Though, having read the comment, I agree that this is overkill for what you're doing.

You just need to set a condition for a While loop:

boolean goodAnswer = false;

while goodAnswer == false{
   System.out.println("Day Input:");
   day=in.nextInt();

  if (day<31) { goodAnswer=true; }
}

A routine like this will effectively keep on asking for an integer until it gets one it likes. Only then will it leave the loop. This is a fairly common approach for this sort of thing.

You would be looking for something of an assertion/validation, which is usually done on a method's arguments:

public void doSomething(int num) {
    if (num > 30) {
        throw new IllegalArgumentException("num is too high!");
    }
    //continue knowing that num is <= 30
}

There are APIs (like Apache Commons) which simplify this to one line:

Validate.isTrue(num <= 30, "num is too high!");

Which does the same code in essence as above, but much shorter.

All of this is a part of Data Validation

For doing a logical loop on this:

boolean valid = false;
while (!valid) {
    try {
        //take input, pass to #doSomething
        valid = true;
    } catch (IllegalArgumentException ex) {
        //repeat / error out
    }
}
//continue

Though you may wish to just manually validate yourself with something like an isValid check:

private boolean isValidDay(int num) {
    return num > 0 && num < 31;
}

//In method
Validate.isTrue(isValidDay(num), "num is not valid!");

//Without try/catch
if (isValidDay(num)) {
    //call #doSomething etc
}

You should not be using the try/catch at all.

There are two types of Exceptions in Java - Caught/Checked Exceptions and Uncaught/Unchecked Exceptions (RuntimeException, Error, and their subclasses). The Exception in your case is an example of an Uncaught/Unchecked Exception as this happens during runtime due to user input.

You do not need try/catch blocks for these exceptions for the most part. In fact, you do not even need to handle these exceptions. So what do you do?

You improve your logic in the code so that the exception does occur. For example, you can use a while loop to keep asking the user for a valid number.

if(day > 30) {
    While(day > 30) {
        //send message to the user 
        day = in.nextInt();    
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM