Throws or try-catch(投掷或尝试接住)
问题描述
在决定是向方法添加 throws
子句还是使用 try-catch
时,一般的经验法则是什么?
What is the general rule of thumb when deciding whether to add a throws
clause to a method or using a try-catch
?
根据我自己的阅读,当调用者违反合同的结尾(传递的对象)时应该使用 throws
并且应该使用 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:通过 Google 和 SO 进行搜索,但希望对此有明确的答案.
P.S: Searched through Google and SO but would like a clear answer on this one.
推荐答案
- 只有在您能够以有意义的方式处理异常时才捕获异常
- 如果要由当前方法的使用者处理,则声明向上抛出异常
- 如果异常是由输入参数引起的,则抛出异常(但这些通常是未经检查的)
这篇关于投掷或尝试接住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:投掷或尝试接住


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01