繁体   English   中英

在Java中返回异常对象

[英]Return exception object in java

我写了一个自定义异常:

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 我们可以做到吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM