通常,我会这样做:
try
{
code
code that might throw an anticipated exception you want to handle
code
code that might throw an anticipated exception you want to handle
code
}
catch
{
}
Run Code Online (Sandbox Code Playgroud)
这样做有什么好处吗?
code
try
{
code that might throw an anticipated exception you want to handle
}
catch
{
}
code
try
{
code that might throw an anticipated exception you want to handle
}
catch
{
}
code
Run Code Online (Sandbox Code Playgroud)
更新:
我最初问这个问题w /引用C#,但正如A. Levy评论的那样,它可以应用于任何异常处理语言,所以我让标签反映了这一点.
我的程序正在处理一些JSON数据.我希望程序在一段时间内保持稳定,JSON数据可以随着源的更新和改进而改变.这是从数据中返回一些图像文件名的当前函数:
@Override
public String createImgName() {
try {
// data["image"]["full"]
return getJSONData().getJSONObject("image").getString("full");
}
catch(JSONException e) {
try {
// data["id"] + ".png"
return getJSONData().getJSONObject("id")+".png";
}
catch(JSONException e2) {
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
还有一些我try可以获得图像名称的东西.但该计划将变得非常丑陋.
在try成功之前是否存在多种事物的语法?在我的情况下,该return声明打破了成功的程序,但可能并非总是如此.