代码之家  ›  专栏  ›  技术社区  ›  NikitaJ

我是否可以使用多个try-catch块来抛出多个错误或异常[已关闭]

  •  1
  • NikitaJ  · 技术社区  · 8 年前

    下面的代码是通过java执行的git push命令的所有内容,如果我运行时不使用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、用户名和密码中的任何一个值不正确,它总是会给出类似“无效用户名和密码”的消息

    1 回复  |  直到 8 年前
        1
  •  4
  •   parlad    8 年前

    尝试创建自定义验证器

    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;
      }
     }
    

    添加您的函数。

    引发ValidationErrorException

    然后使用

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

    用户名和密码等。