返回java中的异常对象

返回java中的异常对象,java,object,exception,return,Java,Object,Exception,Return,我编写了一个自定义异常,如下所示: public class CustomException extends Exception { public CustomeException(String message) { super(message); } } 并尝试以下测试: public static String test(String string) throws CustomException { if (string == null) { thro

我编写了一个自定义异常,如下所示:

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时,
testexpection
对象将是
customexpection
。我们能做到吗?

这是专为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
而不是
customeeexception
,并在其他地方进行相同的更改,这是为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
而不是
customeeexception
,并在其他地方进行相同的更改

谢谢,但是我们可以忽略try-catch块吗?我看到一些例子,他们只是写为``if(string==null)对不起,遗漏了一些东西。我的意思是它们写为:```if(string==null){throw new CustomException(“空字符串”);}``谢谢,但是我们可以忽略try-catch块吗?我看到一些例子,他们只是写为``if(string==null)对不起,遗漏了一些东西。我的意思是,它们写为:```如果(string==null){抛出新的CustomException(“空字符串”);}``在我看来,您正走上一条黑暗的道路。例外情况适用于例外情况。如果您希望返回错误信息而不是引发异常,那么您可能不希望异常,而是希望其他值对象返回信息实际上我在Spring Boot Web App中使用自定义异常。无论何时rest控制器遇到我的异常,它都会抛出异常,我的意思是rest控制器将返回异常对象(timestamp、errorCode、message、exceptionClass、path)。在我看来,您正在走一条黑暗的道路。例外情况适用于例外情况。如果您希望返回错误信息而不是引发异常,那么您可能不希望异常,而是希望其他值对象返回信息实际上我在Spring Boot Web App中使用自定义异常。无论何时rest控制器遇到我的异常,它都会抛出异常,我的意思是rest控制器将返回异常对象(时间戳、错误代码、消息、exceptionClass、路径)