有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java类、异常、用户输入

我有一个使用switch的驱动菜单类,在这个类旁边,当输入错误的输入时,这个类会抛出一个异常。我如何在异常之后返回并要求用户再次输入数据

java类钻石:

public class Diamond 
{

private int x;

    public Diamond(int x) throws IllegalArgumentException 
    {
        if ((x % 2) == 0) 
        {
           System.out.println("\nx must be odd.");
           throw new IllegalArgumentException("x must be odd.");

        }
      this.x = x;

    }

共 (1) 个答案

  1. # 1 楼答案

    请看this question regarding exceptions in generalthis Java Tutorial

    我假设您有一些代码接受用户输入,然后创建Diamond类的实例

    您可以将创建Diamond实例的代码包装在try-catch块中

    比如说:

    Diamond d = null;
    try{
        d = new Diamond(userInput);
    }catch(IllegalArgumentException e){
       //Handle the exception
    }
    

    然而,由于这个异常是由于输入问题而不是编程问题引发的,所以我倾向于在这里使用选中的异常

    根据Java Tutorial的一般规则:

    If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.