Java创建自定义异常错误

x33g5p2x  于2022-12-04 转载在 Java  
字(4.3k)|赞(0)|评价(0)|浏览(679)

本指南将指导您完成如何在Java项目中创建自定义异常。

编写自己的异常类

以下是创建自定义例外的步骤:

  • 创建一个新类,其名称应该以 Exception 结尾,如 ClassNameException。这是一个区分异常类和常规类的约定。
  • 使类 extends 成为 *java.lang.Exception * 类的子类型异常之一。通常,自定义异常类总是直接从 Exception 类扩展。
  • 创建一个带有 String 参数的构造函数,该参数是异常的详细信息。在这个构造函数中,只需调用超级构造函数并传递消息。在Java中,有两种类型的异常-检查异常和未检查异常。

以下是总结:

  • 选中的异常 * -扩展 java.lang.Exception,对于可恢复的条件,需要 try-catch 显式处理异常,编译错误。
  • Unchecked Exceptions* --扩展了 java.lang.RuntimeException,用于不可恢复的情况,如编程错误、不需要try-catch、运行时错误。

让我们创建一个名为 ResourceNotFoundException 的自定义异常。通常,*ResourceNotFoundException * 自定义异常在未找到请求的资源时由服务层抛出。
现在,我们将通过示例讨论如何创建选中和未选中的自定义异常。

自定义选中异常

如果客户端能够从异常中恢复,则将其设置为选中异常。

public class ResourceNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;

    public ResourceNotFoundException(Object resourId) {
        super(resourId != null ? resourId.toString() : null);
    }
}

如何在应用程序中使用 ResourceNotFoundException 自定义异常?

public class TestResourceNotFoundException {
    public static void main(String[] args) throws ResourceNotFoundException {
         ResourceManager manager = new ResourceManager();
         manager.getResource(0);
    }
}

class Resource {
    private int id;

    public Resource(int id) {
        super();
        this.id = id;
    }
}

class ResourceManager {
    public Resource getResource(int id) throws ResourceNotFoundException {
        if (id == 10) {
             new Resource(id);
        } else {
             throw new ResourceNotFoundException("Resource not found with id ::" + id);
        }
        return null;
    }
}

class ResourceNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;

    public ResourceNotFoundException(Object resourId) {
        super(resourId != null ? resourId.toString() : null);
    }
}

输出:

Exception in thread "main" com.ramesh.corejava.devguide.exceptions.customexceptions.ResourceNotFoundException: Resource not found with id ::0
 at com.ramesh.corejava.devguide.exceptions.customexceptions.ResourceManager.getResource(TestResourceNotFoundException.java:26)
 at com.ramesh.corejava.devguide.exceptions.customexceptions.TestResourceNotFoundException.main(TestResourceNotFoundException.java:6)

自定义未选中异常

如果客户端无法从异常中恢复,则将其设置为unchecked异常。

public class BaseRuntimeException extends RuntimeException {
  
    private static final long serialVersionUID = 1L;

    private int statusCode = 500;

    public BaseRuntimeException() {
        super();
    }

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

    public BaseRuntimeException(BaseException be) {
        super(be.getMessage(),be);
        this.statusCode = be.getErrorCode();
    }

    public BaseRuntimeException(Throwable t) {
        super(t.getMessage(),t);
    }

    public BaseRuntimeException(String message, Throwable t) {
        super(message, t);
    }

    public BaseRuntimeException(int status, String message, Throwable t) {
        super(message, t);
        this.statusCode = status;
    }

    public BaseRuntimeException(String message, Throwable t,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, t, enableSuppression, writableStackTrace);
    }

    public int getStatusCode() {
        return statusCode;
    }
}

如何在应用程序中使用 BaseRuntimeException 自定义异常。

public class TestRunTimeException {
    public static void main(String[] args) {
        List<String> data = new ArrayList<>(Collections.nCopies(100, "Ramesh"));
        processData(data);
    }
 
    public static void processData(List<String> data){
        if(data.size() > 50){
             throw new BaseRuntimeException("Image file size con't exceed :: " + 10000000);
        }
    }
}

输出:

Exception in thread "main" com.ramesh.corejava.devguide.exceptions.customexceptions.BaseRuntimeException: Image file size con't exceed :: 10000000
 at com.ramesh.corejava.devguide.exceptions.customexceptions.TestRunTimeException.processData(TestRunTimeException.java:15)
 at com.ramesh.corejava.devguide.exceptions.customexceptions.TestRunTimeException.main(TestRunTimeException.java:10)

更多示例

我个人在日常项目工作中使用的自定义异常很少。

BadRequestException自定义异常错误

  • BadRequestException* 自定义异常是当请求参数错误时由服务层抛出的。
public class BadRequestException extends Exception {
    private static final long serialVersionUID = 1L;

    public BadRequestException() {
        super();
    }

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

    public BadRequestException(String message, Throwable t) {
        super(message, t);
    }

    public BadRequestException(Throwable t) {
        super(t);
    }
}

ResourceNotFoundException自定义异常

找不到请求资源时,服务层引发ResourceNotFoundException自定义异常

public class ResourceNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;

    public ResourceNotFoundException(Object resourId) {
        super(resourId != null ? resourId.toString() : null);
    }
}

UnauthorizedRequestException自定义异常错误

当请求参数错误或用户未授权时,服务层会抛出UnauthorizedRequestException自定义异常。

public class UnauthorizedRequestException extends Exception {
    private static final long serialVersionUID = 1L;

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

相关文章