throw
throw关键字用来在程序中(方法体中)明确的抛出异常
@SuppressWarnings("unchecked")
private <T> T execute(final ChannelCallback<T> action, final ConnectionFactory connectionFactory) {
if (this.retryTemplate != null) {
try {
return this.retryTemplate.execute(new RetryCallback<T, Exception>() {
@Override
public T doWithRetry(RetryContext context) throws Exception {
return RabbitTemplate.this.doExecute(action, connectionFactory);
}
}, (RecoveryCallback<T>) this.recoveryCallback);
}
catch (Exception e) {
if (e instanceof RuntimeException) {
// 抛出异常类实例
throw (RuntimeException) e;
}
throw RabbitExceptionTranslator.convertRabbitAccessException(e);
}
}
else {
return doExecute(action, connectionFactory);
}
}
throws
throws语句用来声明方法不能处理的异常,throws 用在函数上,后面跟的是异常类
// 声明方法不能处理的异常IllegalStateException
private MessageConverter getRequiredMessageConverter() throws IllegalStateException {
MessageConverter converter = this.getMessageConverter();
if (converter == null) {
throw new AmqpIllegalStateException(
"No 'messageConverter' specified. Check configuration of RabbitTemplate.");
}
return converter;
}
本文深入探讨了Java中的异常处理机制,详细解释了throw关键字如何用于显式抛出异常,以及throws语句如何声明方法可能抛出的异常。通过具体代码示例,展示了如何使用throw重新抛出异常和如何使用throws声明方法不能处理的异常。
690

被折叠的 条评论
为什么被折叠?



