【发布时间】: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