繁体   English   中英

创建类似于C#异常的Java异常

[英]Creating a Java Exception that is similar to a C# Exception

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

您始终可以创建自定义异常,并且只需要对它们进行不必要的处理

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。

暂无
暂无

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

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