java - 冒泡一个异常:Java
问题描述
所以我有一个方法,如果发生异常,我想在方法中重试操作。如果异常再次发生,我希望在另一个类调用该方法的地方捕获异常。这是正确的方法吗?
public OAuth2AccessToken getAccessTokenWithRefreshToken (String refreshToken) throws OAuth2AccessTokenErrorResponse, IOException, InterruptedException ,ExecutionException {
try {
System.out.println("trying for the first time");
OAuth2AccessToken mAccessToken = mOAuthService.refreshAccessToken(refreshToken);
return mAccessToken;
catch (IOException | InterruptedException | ExecutionException e) {
try {
System.out.println("trying for the second time");
OAuth2AccessToken mAccessToken = mOAuthService.refreshAccessToken(refreshToken);
} catch (IOException | InterruptedException | ExecutionException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
throw e2;
}
}
return mAccessToken;
}
解决方案
最好使用循环,以免重复:
public OAuth2AccessToken getAccessTokenWithRefreshToken (String refreshToken) throws OAuth2AccessTokenErrorResponse, IOException, InterruptedException ,ExecutionException {
int maxAttempts = 2;
int attempt = 0;
while (attempt < maxAttempts) {
try {
return mOAuthService.refreshAccessToken(refreshToken);
}
catch (IOException | InterruptedException | ExecutionException e) {
attempt++;
if (attempt >= maxAttempts) {
throw e;
}
}
}
return null; // or throw an exception - should never be reached
}
推荐阅读
- javascript - 在 MediaRecorder 的 dataavailable 事件中分别播放每个音频块
- css - Python-Sphinx:设置文本正文字体
- android - 通用应用链接和多个调试 SHA256 指纹
- sql - 限制 SQL 查询结果中的重复行数
- webhooks - 创建具有范围 = 项目 id 但适用于顶级文件夹的 webhook 时出错
- node.js - 使用 spawn 方法从电子应用程序运行子进程的问题
- c++ - 如果函数使用 OPENCV Mat 作为输入,如何编写头文件?
- javascript - 如何使用 vanilla JS 在第二个元素上添加/删除类?
- c++ - 优化使用 C++ 在 SQLite DB 中查询超过 5000 万条数据记录的方式
- java - 如何获取多个Edit Text addview android的值并将其发送到MySQL