如何在Try / Catch块中引发异常?

卡罗琳 :

我有以下Java方法:

public Class createClass(Class class) {
    try {
        // retrieve the professor of the class and check if he exists
        Professor professorFound = professorRepository.findById(class.getProfessorId());
        if (professorFound != null) {
           // if the professor exists, then check if he already has a class
           // with the same id
           List<Class> classes = professorFound.getClasses();
           List<Class> classFound = classes.stream().... // loop to find the class... 

           // if he has, throw an exception
           if(!classFound.isEmpty()) {
                throw new ClassAlreadyRegisteredException();

           } else {
                // if he does not have, then create the class
                Class class = new Class();
                professorFound.getClasses().add(class);
                return professorRepository.save(professorFound);
           }
        } else {
           // if the professor does not exist, throw an exception
           throw new ProfessorNotFoundException();
    } catch (Exception e) {
        // if there is any other error during the communication with the database, 
        // throw a generic IOException
        throw new ClassIOException();
    }
}

基本上,我需要抛出特定的异常(如果在请求中通知的教授不存在,或者教授已经具有相同的ID的类),或者IOException在与之通信期间出现任何其他错误,则抛出一个泛型。数据库。

但是,按照我开发的方式,如果Exception抛出任何特定的异常,try块将捕获异常并抛出通用的IOException。

我怎么解决这个问题?

我对了解这种情况下的最佳做法非常感兴趣。 我应该分别捕获每个特定的异常并抛出两次吗? 这是一个好习惯吗?

编辑:

这是我的ClassAlreadyRegisteredException样子:

public class ClassAlreadyRegisteredException extends ApiException {

    private static final long serialVersionUID = 1L;

    public ClassAlreadyRegisteredException(String code, String message, String developerMessage, String origin, HttpStatus status) {
        super(code,message,developerMessage,origin, status);
    }
}

这是我的ApiException样子:

@Data
@AllArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class ApiException extends RuntimeException{
    
    private static final long serialVersionUID = 1L;
    
    private String code;
    private String userMessage;
    private String developerMessage;
    private String origin;
    private HttpStatus status;
}

提前致谢。

shinjw:

已检查与未检查的异常

在catch块中引发异常是完全可以接受的。一个常见的用例是选中Exception并抛出未选中的代码RuntimeException,这将允许异常冒泡到达需要处理的地方。

您需要将已检查的异常用于连接/ IO,SQL异常等用例。

处理检查的异常

为了回答您的问题,在大多数连接到数据库的库中,IOException如果存在任何连接问题,将对其进行检查对于这些情况,您始终可以在方法签名中指定它public Class createClass() throws IOException

这指定的任何调用者createClass()必须履行IOException处理的合同

要么

您可以将其作为 RuntimeException

try {
   ...
} catch (IOException e) {
   throw new RuntimeException(e); // <- send the original exception so you can preserve the exception and stacktrace.
}

实际上,这将上升到STDOUT或框架指定的任何处理程序。

警告:

但是,全力以赴Exception并投掷更具体的内容ClassIOException可能会带来意想不到的后果。

如果您有一个,NullPointerException这将被您的catch (Exception e)方块捕获并重新抛出ClassIOException

这样做会破坏堆栈跟踪,并导致错误日志的调试更加困难。

了解什么构成了检查的异常。

另一个提示是考虑您的Exception情况。

如果它们是应用程序,服务或业务逻辑的标准流程,则可能不是适当的例外。

在您的申请中ClassAlreadyRegisteredExceptionProfessorNotFoundException可能不是特殊情况...除非您的教授已经指定了这些情况。

有时,可能会RuntimeException根据情况需要抛出这些错误。

最佳做法?

关于如何处理异常,仍然有很多意见。所以这是一些例外情况处理时我会问自己的一些经验法则问题

  1. 是否保留了堆栈跟踪?我将能够追溯到根异常
  2. 这是通用逻辑,是否代表与我的应用程序提供的内容不同的例外情况?
  3. 如果抛出此异常,则调用此方法来处理这种特殊逻辑的任何人绝对必要吗?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Visual Studio 2015在Try Catch块中引发异常

如何调用在catch块中引发异常的方法?

如何在嵌套的try / except块中重新引发异常?

如何在嵌套的try / except块中重新引发异常?

我如何在try块中引发异常并终止程序

try块引发异常,但catch块未捕获异常

如何在不引发Java异常的情况下摆脱try / catch块

Java运行代码是否仅在try和catch块中未引发异常的情况下?

为什么引发异常的此方法在调用时不必放在try catch块中?

如何从Java的try / catch块中引发异常的那一刻起恢复执行?

如何引发异常并在catch块中执行其余的业务逻辑?

如何在异步函数内的try / catch块中引发错误?

如何在一个“ Try”块中引发同一错误的多个异常

try / catch块中未处理的异常

在 try/catch 块中未捕获异常

在 try catch 块中重试异常

异常未捕获在try catch块中

如何在其他try catch块中处理异常?

在调用引发异常的方法时,如何避免在try catch块中出现伪返回?

我如何在C ++中的catch块中处理异常

在引发之前恢复 python try 异常块中的更改

永远不会在相应的try块中引发异常

C ++如何在try catch块中处理分配?

我该如何在Mockito中测试try and catch块?

如何在try catch块中返回IEnumerable对象?

如何在 try/catch 块中重构这个 If/else 语句?

检查是否在try..catch..finally中引发了异常

在单元测试try / catch中未捕获引发的异常

我可以利用多个try catch块引发多个错误或异常