简体   繁体   English

Java 中的异常 - Try/Catch

[英]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.我正在学习 Java,我有这个程序可以根据用户编写的日期和月份来告诉符号。 The program works as it is, but if the user enters a day like 90 or so, the program doesnt evaluate that "error".该程序按原样运行,但如果用户输入 90 天左右,该程序不会评估该“错误”。 Can I correct this with a try/catch?我可以通过 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.我也会重写你的 getSign() 方法,混合开关和 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();你也可以提取你的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:您只需要为 While 循环设置条件:

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:有一些 API(如 Apache Commons)将其简化为一行:

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:尽管您可能希望使用 isValid 检查之类的东西手动验证自己:

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.您根本不应该使用 try/catch。

There are two types of Exceptions in Java - Caught/Checked Exceptions and Uncaught/Unchecked Exceptions (RuntimeException, Error, and their subclasses). Java 中有两种类型的异常 - 捕获/检查异常和未捕获/未检查异常(RuntimeException、Error 及其子类)。 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.大多数情况下,您不需要 try/catch 块来处理这些异常。 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.例如,您可以使用 while 循环不断向用户询问有效数字。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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