Java程序中自带catch,如何避免在java中尝试catch块

I'm very new to java and the idea of try catch blocks to handle exceptions.

This roughly what I'm ending up with, and there simply has to be a better way:

try {

JSONObject jsonObject = new JSONObject(jsonString);

int aCount = jsonObject.getInt("acount");

String devTok = jsonObject.getString("dt");

String qURL = jsonObject.getString("qu");

try {

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

Key qKey = KeyFactory.createKey("qu", qURL);

int dsACount = (Integer) datastore.get(qKey).getProperty(kLastKnownANumber);

//..etc.. more try catch blocks needed

} catch (EntityNotFoundException e) {

e.printStackTrace();

}

} catch (com.google.appengine.repackaged.org.json.JSONException e) {

e.printStackTrace();

}

There are more try catch blocks embedded in the same way, so that at the end, there is just a lump of catch blocks. How else should exceptions be handled, Eclipse keeps asking my to either surround with a try catch block or "Add throws declaration".

Sometimes I want to catch certain exceptions, for example if it can't find an entity, I want to print something like "Entity not found", and if the JSON string can't be parsed into an object, I want to print something like "Can't parse JSON".

(I'm used to objective-c where the are delegate methods for failure, or the method returns null and you have passed a pointer to [a pointer to] an NSError object, which will have been "filled", Is there somewhere to learn about try-catch?)

解决方案

If all you're doing is catching them and printing the stack trace regardless of the exception type, you can just wrap the code in one large try/catch block. To save many "catches", you can catch java.lang.Throwable which is the interface that all exceptions implement. If not, you can have a catch for every type of checked exception the code you're calling throws, and handle them specifically.

Eclipse keeps asking you to do so because Java code will not compile if the checked exceptions are not caught, or declared to be thrown by the caller.

+Adding this comment to the answer (Thanks, Paul Tomblin):

In production quality apps you'd be logging the trace, adding some logic where you're handling the exception in a right way, taking an alternate flow, and/or re-wrapping it in another exception and throwing it, etc. It all depends on the particular problem you're trying to solve.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值