我可以使用多个 try catch 块来抛出多个错误或异常吗

Can I make use of multiple try catch blocks to throws multiple errors or exceptions

下面的代码是 git 通过 java 推送命令的所有内容,如果我 运行 没有使用 try catch 块它成功推送文件,但我不知道如何抛出错误如果用户使用 try 和 catch 块输入错误的 url 以及用户名和密码,任何人都可以在代码中对其进行正确的编辑。

  public void pushRepo (String repoUrl, String gitdirectory, String username, String password) throws GitAPIException
{

      Git git = null;
    try {
        git = Git.open(new File(gitdirectory));
    } catch (IOException e1) {
        System.out.println("it is not git directory");
    }
      RemoteAddCommand remoteAddCommand = git.remoteAdd();
      remoteAddCommand.setName("origin");
      try {
      remoteAddCommand.setUri(new URIish(repoUrl));
      System.out.println("file added");
      }catch (Exception e) {
           System.out.println("Invalid RemoteUrl");
        }
      remoteAddCommand.call();
      git.add().addFilepattern(".").call();
      git.commit().setMessage("commited").call();
      PushCommand pushCommand = git.push();
      try {
      pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
      pushCommand.setRemote("origin").add("master").call();
      System.out.println("push file");
      }catch(Exception e)
      {
          System.out.println("Invalid username and password");
      }

    }
}

如果我输入的任何 url、用户名和密码的值不正确,它总是会显示类似 "invalid username and password."

的消息

尝试制作自定义验证器

public class ValidationErrorException extends Exception {

private List<String> errors;

public ValidationErrorException(List<String> errors) {
    super("Validation Errors.");
    setErrors(errors);
}

public ValidationErrorException(String message, List<String> errors) {
    super(message);
    setErrors(errors);
}

public void setErrors(List<String> errors) {
    this.errors = errors;
}

public List<String> getErrors() {
    return errors;
  }
 }

添加你的函数。

throws ValidationErrorException

然后使用

try {
        // write code for check url
    } catch (Exception ex) {
        List<String> errors = new ArrayList<>();
        errors.add("Invalid URL...");
        throw new ValidationErrorException(errors);
    }

用户名和密码依此类推。