自定义异常-Java

Custom Exception-Java

好吧,我正在为客户编写一个租车系统,他们有身份证。在租车时,客户需要使用 id 来标识自己,所以我需要一个自定义异常来处理用户输入的是 8 个数字和一个字母,例如:

55550000A

我已经对输入是否为 int 进行了例外处理:

   import java.util.*;
   import java.util.Scanner;
public class read {
static Scanner leer=new Scanner(System.in);
public static int readInt() {
    int num = 0;
    boolean loop = true;

    while (loop) {
        try {
            num = leer.nextInt();
            loop = false;
        } catch (InputMismatchException e) {
            System.out.println("Invalid value!");
            System.out.println("Write again");
    leer.next();
         } 
      }
    return num;
  }
}

您唯一需要做的就是声明变量并像这样调用方法:

int variable=read.readInt();

所以如果 id 能像那样工作就好了,我的意思是另一种方法 readId() 可以 return 该值。问题是我不知道如何为自定义格式设置例外,或者这是否可能,所以任何帮助都会有所帮助。非常感谢!

你的问题有点令人困惑,但我想你想创建一个新的例外。

创建文件MyAppException.java

class MyAppException extends Exception {

private String message = null;

public MyAppException() {
    super();
}

public MyAppException(String message) {
    super(message);
    this.message = message;
}
}

你可以通过

throw new MyAppException();

但我想你想要的不需要例外:

public static String readId() {
    String id = "";
    while(true){
        id = leer.next();
        try{
            Integer.parseInt(id.substring(0,8));
        }catch(InputMismatchException e){
            System.out.println("Invalid Input");
            continue;
        }
        if(id.length() != 9)continue;
        if(Character.isLetter(id.chatAt(8)))break;
    }
    return id;
}

@epascarello 是正确的,除了他们名字中的Java,他们都是非常不同的,至于问题,尝试像这样自定义异常:

public class InputMismatchException extends Exception {
    public InputMismatchException(String message) {
        super(message);
    }
}

通常,您只想抛出异常以防止某种错误导致您的程序以某种形式完全失败。 更好 的解决方案是在程序稍后使用之前验证输入。创建条件检查输入是否为所需的长度和数据类型,如果不是,则需要重新获取输入。

过度使用异常表明设计不当,如果稍后修改代码,可能会出现严重问题。

通过扩展 Exception 创建您自己的异常 -

class InvalidIdException extends Exception
{
      public InvalidIdException() {}

      public InvalidIdException(String message)
      {
         super(message);
      }
 }

然后从您的客户端 class 检查输入的 ID 是否有效。如果它是一个无效的 id 则 throw InvalidIdException。假设您正在 validateId() 方法中验证您的 ID。然后你可以从这个方法中抛出一个 InvalidIdException -

boolean isValidId(String id) throws InvalidIdException{

    if(id == null){
            throw new InvalidIdException("Id is null");
        }
   else {
    //check for id formatting 
    //for example whether id has it's minimum length
    //contains any character etc.
    throw new InvalidIdException("Id has wrong format");
   }

   return true;
}