创建一个类似于c#异常的Java异常

本文关键字:异常 Java 类似于 一个 创建 | 更新日期: 2023-09-27 18:16:00

我需要在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

创建一个类似于c#异常的Java异常

您总是可以创建自定义异常,您只需要以不同的方式处理它们

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

我的建议如下:

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。