0

我需要在 Java 中创建一个异常,该异常的运行方式与以下 C# 相同。

public class ResponseException : Exception
{
    internal ResponseException(int statusCode, String StatusCodeDescription, String request, String response)
        : base("Returned an error status code " + statusCode.ToString() + " (" + StatusCodeDescription + ") " + response)
    {
        this.StatusCode = statusCode;
        this.StatusCodeDescription = StatusCodeDescription;
        this.Request = request;
        this.Response = response;
    }

    public int StatusCode { get; set; }
    public String StatusCodeDescription { get; set; }
    public String Request { get; set; }
    public String Response { get; set; }
}

目前我找不到以这种方式工作的 Java 异常示例。上面的异常就是这样调用的

throw new ResponseException(((int)response[1]), 
   ((String)response[2]), url, ((String)response[0]));

我通读了以下线程,但它们并没有提供太多关于我将如何进行此操作的见解,或者是否有可能。

如何在 Java 中创建自定义异常类型?

如何在 Java 中创建自定义异常?

http://www.java-forums.org/java-lang/7699-how-create-your-own-exception-class.html

4

2 回答 2

2

你总是可以创建你的自定义异常,你只需要对它们进行不同的处理

class MyException extends Exception {

public int StatusCode;
public String StatusCodeDescription;
public String Request;
public String Response;

public MyException() {
}

public MyException(String msg) {
    super(msg);
}

public MyException(int statusCode, String statusCodeDescription,
        String request, String response) {
    StatusCode = statusCode;
    StatusCodeDescription = statusCodeDescription;
    Request = request;
    Response = response;
}

public int getStatusCode() {
    return StatusCode;
}

public void setStatusCode(int statusCode) {
    StatusCode = statusCode;
}

public String getStatusCodeDescription() {
    return StatusCodeDescription;
}

public void setStatusCodeDescription(String statusCodeDescription) {
    StatusCodeDescription = statusCodeDescription;
}

public String getRequest() {
    return Request;
}

public void setRequest(String request) {
    Request = request;
}

public String getResponse() {
    return Response;
}

public void setResponse(String response) {
    Response = response;
}

}

并使用

throw new MyException(((int)response[1]), ((String)response[2]), url, ((String)response[0]));
于 2013-05-29T17:41:45.727 回答
0

我建议如下:

public class ResponseException extends Exception {

   private int statusCode;
   private String statusCodeDescription;
   private String request;
   private String response;

   public ResponseException(int statusCode, String statusCodeDescription, String request, String response) {
      super("Returned an error status code " + statusCode + " (" + statusCodeDescription + ") " + response);
      this.statusCode = statusCode;
      this.statusCodeDescription = statusCodeDescription;
      this.request = request;
      this.response = response;
   }
}

在这个例子中只是缺少 Getter 和 Setter。

于 2013-05-29T17:44:20.687 回答