您什么时候希望声明异常,而不是在Java中处理它? [英] When would you prefer to declare an exception rather than handling it in Java?
问题描述
编辑:我的意思是在最后一行调用方法而不是超级类。
一般来说,我会说设计你的异常流程,以便异常被实际采取适当的操作的代码所捕获。
这通常意味着在库方法(或大型项目中的某种通用实用方法)中,您将抛出不捕获它们的异常。
On另一方面,如果你有一种情况,你发现自己宣布你的方法抛出一个你相信实践中几乎不会发生的异常(例如序列化通常涉及到实际上不会发生的各种假的检查异常,例如你反序列化整数,真的不太可能,Integer类不存在,但您仍然必须捕获适当的异常),那么您有第三个选项重新转换为RuntimeException。
I know we can declare the exception for our method if we want it to be handled by the calling method. This will even allow us to do stuff like write to the OutputStream without wrapping the code in try/catch block if the enclosing method throws IOException.
My question is: Can anyone provide an instance where this is usually done where you'd like the calling method to handle the exception instead of the current method?
Edit: I meant calling method instead of super class in the last line.
In general, I would say design your exception flow so that the exception is caught by the code that can actually take appropriate action.
This usually means that in a "library" method (or, some kind of general utility method in a large project), you will be throwing exceptions not catching them.
On the other hand, if you have a situation where you find yourself declaring your method to throw an exception that you believe in practice will hardly ever occur (e.g. serialisation generally involves all sorts of spurious checked exceptions which in practice won't occur, e.g. if you're deserialising an Integer, it's really unlikely that the Integer class is not present, but you still have to catch the appropriate exception), then you have a third option of re-casting to a RuntimeException.
这篇关于您什么时候希望声明异常,而不是在Java中处理它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!