fro*_*die 3 java runtime exception checked-exceptions
我有一个异常链,其中method1
抛出一个异常method2
抛出异常的异常main
.由于某种原因,编译器强制我处理错误method2
并将其标记为错误,如果我不这样做,表明它是一个已检查的异常.但是当相同的Exception
内容向下抛出时main
,编译器允许我忽略它并且不显示任何错误.
原来的Exception method1
是a ParseException
,经过检查.但是该方法throws Exception
在头文件中有一个泛型子句,并且同一个对象被抛出到method2,它具有相同的throws Exception
子句.此异常何时以及如何失去编译器检查/捕获的状态?
编辑澄清:
public void method1() throws Exception{
// code that may generate ParseException
}
public void method2() throws Exception{
method1(); //compiler error (if the throws clause is left out)
}
public static void main(String[] args){
method2(); //ignored by compiler, even though the exception isn't caught or thrown or handled at all
}
Run Code Online (Sandbox Code Playgroud)
编辑:
对不起大家,问题是基于一个错误...主要方法实际上有一个throws Exception
我失踪的条款.我已删除它,代码现在表现如预期.感谢您的帮助!
是否检查异常完全取决于它是什么类型的异常:如果它是它的一个RuntimeException
或子类,则不检查它; 否则就是.(是的,RuntimeException
是Exception
Java库设计失败之一的子类,但不是最重要的.)
编译器检查的是方法签名.因此抛出的实际异常是无关紧要的(为此目的).如果方法说throws Exception
那么你必须抓住Exception
你的方法或声明该方法throws Exception
.方法应始终使用最窄的 throws
条款 - 例如,但不是 .throws Exception
throws ParseException
(我说"无关紧要(为了这个目的)",因为当然,编译器要做的其他事情之一是检查你是否抛出了你的throws
子句未涵盖的已检查异常.)
编辑您在编辑中添加的代码将无法编译:1.它在没有实例的情况下调用实例方法,并且2. main
需要声明它会抛出Exception
.
此代码解决了其他问题,并且(正确地)证明main
需要该throws Exception
子句:
public class CheckTest
{
public static final void main(String[] params)
{
new CheckTest().method2();
}
public void method1() throws Exception{
throw new java.text.ParseException("foo", 2);
}
public void method2() throws Exception{
this.method1();
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
CheckTest.java:27: unreported exception java.lang.Exception; must be caught or declared to be thrown
new CheckTest().method2();
^
1 error
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
332 次 |
最近记录: |