java 如何为整个类抛出异常而不是逐个方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4405940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I throw an exception for the whole class instead of doing it method by method
提问by Dream Lane
I'm writing a program in Java, and nearly every method in one of my classes is written like:
我正在用 Java 编写一个程序,我的一个类中的几乎每个方法都是这样编写的:
public void doStuff() throws AWTException{}
Is there a way for me to get rid of the extra step of typing throws AWTException for each method, and somehow do it for the entire class?
有没有办法让我摆脱为每个方法键入 throws AWTException 的额外步骤,并以某种方式为整个类执行此操作?
回答by Asaph
Sorry, No. There is no way to do this in Java.
抱歉,不可以。在 Java 中没有办法做到这一点。
回答by Ravi Parmar
if you throw exception with class level then how you identify that on which type of exception is thrown by method... or on which method it throw exception.
如果您在类级别抛出异常,那么您如何识别方法抛出的异常类型......或抛出异常的方法。
so it is not allow in java...and also its not a good coding with java
所以它在java中是不允许的......而且它也不是一个很好的java编码
回答by Aditya
You can by throw exception at constructor level. You can see how FileInputStream force us to throw IO exception while creating object of it.
您可以在构造函数级别抛出异常。您可以看到 FileInputStream 如何强制我们在创建它的对象时抛出 IO 异常。