在meth2()
下面的代码块中抛出ExcepOne
和ExcepTwo
,自定义异常,扩展Exception
,以便检查它们。但是,当我碰巧为IOException
编写另一个catch块时,我收到一个编译错误,指出IOException
已被捕获。为什么会显示出来?它被抓到了哪里?
public class ExceptionConcepts {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ExcepOne{
System.out.println("In main method");
try{
meth1();
}catch(ExcepOne e1)
{
System.out.println("Finally caught ExcepOne");
}
}
public static void meth1() throws ExcepOne{
try{
meth2();
}catch(ExcepTwo e2)
{
System.out.println("In meth1 catch for Exceptwo");
throw new ExcepOne("1ond");
}
catch(ExcepOne e1)
{
System.out.println("In meth1 catch for ExcepOne");
}
catch(IOException ie) // I get a compilation error here
{
}
}
public static void meth2() throws ExcepOne,ExcepTwo{
int i=-1;
try{
if(i<0)
throw new ExcepOne("one");
else
throw new ExcepTwo("two");
}
catch(ExcepTwo e1)
{
System.out.println("in catch of ExcepTwo");
throw new ExcepTwo("2");
}
catch(ExcepOne e2)
{
System.out.println("in catch of ExcepOne");
throw new ExcepOne("1");
}
finally
{
System.out.println("I am finally");
throw new ExcepTwo("2");
}
}
}
public class ExcepOne extends Exception()
{
public ExcepOne(String msg)
{
super(msg);
}
}
public class ExcepTwo extends Exception()
{
public ExcepTwo(String msg)
{
super(msg);
}
}
答案 0 :(得分:0)
你错过了:
import java.io.IOException;
当你将它添加到你的来源时,会发生以下两件事之一:
- 如果try块可以抛出IOException
,程序将编译。
- 否则你将得到汇编error: exception IOException is never thrown in body of corresponding try statement