您什么时候希望声明异常,而不是在Java中处理它? [英] When would you prefer to declare an exception rather than handling it in Java?

查看:165
本文介绍了您什么时候希望声明异常,而不是在Java中处理它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如果我们希望通过调用方法来处理我们的方法,我们可以声明异常。这甚至允许我们在写入OutputStream时,如果封装方法抛出IOException,则不会在try / catch块中包装代码。我的问题是:任何人都可以提供一个实例,通常情况下,您希望调用方法来处理异常而不是当前的方法?



编辑:我的意思是在最后一行调用方法而不是超级类。

解决方案

一般来说,我会说设计你的异常流程,以便异常被实际采取适当的操作的代码所捕获。



这通常意味着在库方法(或大型项目中的某种通用实用方法)中,您将抛出不捕获它们的异常。



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屋!

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