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

标签 c# java 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]));


我通读了以下主题,但是他们并没有对我如何解决甚至没有可能提供太多的见解。

How to create a custom exception type in Java?

How to create custom exceptions in 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]));

关于c# - 创建类似于C#异常的Java异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16820360/

相关文章:

java - 从 R : Java version missmatch 调用时 h2o 连接失败

java - 下载内部存储器中的 PDF 文件

java - Hibernate + spring 获取最新的lazy 1 to N 属性值

c# - 如何在 C# 中测试 COM 依赖对象

C# DataGrid 填充了具有多个层的列表

c# - 为什么不需要非GUI线程的某些表单元素调用?

c# - 谁能解释为什么我在使用 MathNet.com Numerics Library 时出现 TypeLoad Exception?

java - Kotlin - Spring REST - 不会调用带有 ExceptionHandler 的 ControllerAdvice

c# - JavascriptSerializer 异常

c# - SqlDataReader 和 SqlCommand