我有以下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;
}
提前致谢。
在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
情况。
如果它们是应用程序,服务或业务逻辑的标准流程,则可能不是适当的例外。
在您的申请中,ClassAlreadyRegisteredException
和ProfessorNotFoundException
可能不是特殊情况...除非您的教授已经指定了这些情况。
有时,可能会RuntimeException
根据情况需要抛出这些错误。
关于如何处理异常,仍然有很多意见。所以这是一些例外情况处理时我会问自己的一些经验法则问题
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句