投掷或尝试+抓住 [英] Throws or try+catch

查看:149
本文介绍了投掷或尝试+抓住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在决定是否向方法添加throws子句或使用try-catch时,通常的经验法则是什么?



从我自己读过的内容当调用者已经破坏了合约(传递对象)的结束时,应该使用throws,并且在方法内执行的操作期间发生异常时应使用try-catch。它是否正确?如果是这样,应该在呼叫方做些什么?



PS:通过Google和SO搜索,但希望对此有一个明确的答复。

解决方案


  • 仅在有意义的方式处理它时才捕获异常

  • 声明如果要由消费者处理当前方法

  • 抛出异常,如果它们是由输入参数引起的(但是这些更常被取消选中),则向上抛出异常。 >

What is the general rule of thumb when deciding whether to add a throws clause to a method or using a try-catch?

From what I've read myself, the throws should be used when the caller has broken their end of the contract (passed object) and the try-catch should be used when an exception takes place during an operation that is being carried out inside the method. Is this correct? If so, what should be done on the callers side?

P.S: Searched through Google and SO but would like a clear answer on this one.

解决方案

  • catch an exception only if you can handle it in a meaningful way
  • declare throwing the exception upward if it is to be handled by the consumer of the current method
  • throw exceptions if they are caused by the input parameters (but these are more often unchecked)

这篇关于投掷或尝试+抓住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆