gpt4 book ai didi

java - 显示已处理某些未处理的已检查异常的异常

转载 作者:太空宇宙 更新时间:2023-11-04 13:26:32 24 4
gpt4 key购买 nike

meth2()下面的代码块中抛出ExcepOneExcepTwo,自定义异常,扩展了Exception,因此它们被检查。但是,当我碰巧为 IOException 编写另一个 catch block 时,我收到一个编译错误,指出 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);
}
}

最佳答案

你失踪了:

import java.io.IOException;

当您将其添加到源中时,将会发生以下两件事之一:
- 如果 try block 可以抛出 IOException 程序将编译。
- 否则你会得到编译错误:异常IOException is never throw in body of相应的try语句

关于java - 显示已处理某些未处理的已检查异常的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32592753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com