public class Action {
public Action(ActionName name) {
this(name, "");
}
public Action(ActionName name, String...args) {
...
act();
}
public Action(String url, String paramStr) {
...
act();
}
private void act() {
try {
response = KanHttpUtil.post(url, paramStr);
} catch (Exception ex) {
Log.toConsole(ex.getMessage());
throw ex; // Actually I can't throw it until I surround it with another try-catch
}
...
}
}
我有这个 Action 类。会经常被调用。如果 http post 出现问题,我需要抛出异常。但是,我不想在每个调用周围编写 try-catch,这些调用也不需要捕获异常。 Action总是由构造方法调用,但是第一个构造方法中的try-catch是不可行的。
现在我很困惑该怎么办。
<小时/>我想对我的代码进行此更改
throw new RuntimeException();
或者我应该将 RuntimeException 扩展为 MyException 并抛出它?
当我调用 Action(ActionName name) 时我可以捕获它吗?
<小时/>按照Ben的要求,我将解释一下该程序的一些细节。 Action 中的 act()
是该类中的核心方法,它发出一个 http 请求并在某种程度上解析响应。我在构造函数中调用它,因为它总是被调用并且没有任务要返回。相反,我有 getResponseCode()
、getResponseData()
来获取信息。我发现进行此调用很简单,int code = new Action(ActionName.A, paramStr).getResponseCode()
。因此,如果 http post 失败或响应不是预期的形式,就会发生失败。
这是KanHttpUtil的源代码
public class KanHttpUtil {
private static String userAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
public static String post(String url, String paramStr) throws Exception {
HttpURLConnection con = null;
// request
if (!url.startsWith("http"))
url = "http://" + Info.getHost() + url;
if (!paramStr.contains("verno"))
paramStr = paramStr + "&api_verno=1";
if (!paramStr.contains("token"))
paramStr = paramStr + "&api_token=" + Info.getToken();
try {
con = (HttpURLConnection) new URL(url).openConnection();
con.setConnectTimeout(30000);
con.setReadTimeout(30000);
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("User-Agent", userAgent);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
osw.write(paramStr.replace("_", "%5F").replace(",", "%2C"));
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
// response
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
}
最佳答案
我能想到的有两种方法:
考虑一下您想在哪里抛出异常并处理它。您可能想捕获它并将其扔到调用层次结构中较低的位置。这种方法的一个很好的场景是,假设您正在逐行读取文本文件,并且您想要简单地忽略坏行(根据您的用例的“坏”的某种定义)。在这种情况下,如果您在阅读器中应用 try-catch 并使其在当前行之后继续
继续
,这将是一个很好的方法。或者,您可以使用
RunTimeException
的子类,前提是您确定无法保证在发生某些异常时您可以 promise 做什么。在大多数情况下,使用运行时异常并不是一个好主意。由于这些是未经检查的异常,因此不需要将它们作为契约(Contract)的一部分明确捕获 - 这可能会导致松散的编码实践可能导致系统/服务崩溃的情况,因为人们没有计划从内部抛出异常RuntimeException block 。这正是发生在我身上的事情。
祝你编码愉快!
关于java - 如何抛出异常而不强制需要catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20793412/