简体   繁体   English

在Java中返回异常对象

[英]Return exception object in java

I wrote a custom exception as: 我写了一个自定义异常:

public class CustomException extends Exception {

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

and try some tests as: 并尝试以下测试:

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

When I run, it throws the exception. 当我运行时,它将引发异常。 I wonder how can it returns the exception object instead of throwing an exception. 我不知道它如何返回异常对象而不是引发异常。

I mean the testExpception object will be CustomExpception when we input the string as null. 我的意思是当我们将字符串输入为null时, testExpception对象将为CustomExpception Can we do it ? 我们可以做到吗?

That's for the try catch is designed for. 这是为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();
    }

 }

Plus there is a typo in you exception constructor.it should be CustomException not CustomeException and make the same change at other places as well 另外,您的异常构造函数中有一个错字。它应该是CustomException而不是CustomeException并在其他地方也进行相同的更改

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

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