【问题标题】:Return exception object in java在java中返回异常对象
【发布时间】:2017-02-24 17:50:42
【问题描述】:

我写了一个自定义异常:

public class CustomException extends Exception {

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

并尝试一些测试:

public static String test(String string) throws CustomException {
    if (string == null) {
      throw new CustomException("Empty String");
    }

    return string;
  }

  public static void main(String[] args) throws CustomException {

    String testException = test(null);
    System.out.print(testException);
  }

当我运行时,它会抛出异常。我想知道它如何返回异常对象而不是抛出异常。

我的意思是当我们将字符串输入为 null 时,testExpception 对象将是 CustomExpception。我们能做到吗?

【问题讨论】:

  • 在我看来,您正走向一条黑暗的道路。例外是针对特殊情况。如果您想返回错误信息而不是引发异常,那么您可能不希望异常而是其他一些值对象返回信息
  • 其实我在 Spring Boot Web App 中使用了自定义异常。每当rest控制器遇到我的异常就会抛出异常,我的意思是rest控制器会返回异常对象(timestamp、errorCode、message、exceptionClass、path)

标签: java object exception return


【解决方案1】:

这是为 try catch 设计的。

 public static void main(String[] args) {
    try{
        String testException = test(null);
    }
    catch(CustomException e){// object e can be used for analysing the exception
        e.printStackTrace();
    }

 }

另外,您的异常构造函数中有一个错字。它应该是 CustomException 而不是 CustomeException 并且在其他地方也进行相同的更改

【讨论】:

  • 谢谢,但是我们可以忽略 try catch 块吗?我看到一些他们只是写成 ```if (string == null) 的例子
  • 抱歉遗漏了一些东西。我的意思是他们写成:``` if (string == null) { throw new CustomException("Empty String"); } ```
猜你喜欢
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
相关资源
最近更新 更多