public Class HelloWorld{
public HelloWorld(){
init();
}
public void init(){
try{
System.out.println("Hello world");
}catch(IOException e){
System.out.println("Error");
}
}
}
public HelloWorld(){
init();
}
public void init(){
try{
System.out.println("Hello world");
}catch(IOException e){
System.out.println("Error");
}
}
}
import java.io.*;public class SL275
{
public static void main(String[] args)
{
// 下面是异常处理
try
{
init();
}
catch(IOException e)
{
System.out.println("The main method had caught a IOException.");
}
// 上面是异常处理
}
public static void init() throws IOException
{
System.out.println("This is method init.");
if (true)
throw new IOException("Exception!!!");
}
}
运行结果是:
This is method init.
The main method had caught a IOException.
也就是说init()里throw了一个异常,自己没有catch,交给了调用init()的main()处理,而main()里有catch,就处理了异常。但是如果把main()两段注释中间的try catch去掉,即不要处理init()抛出的IO异常,按道理不是说编译都通不过吗?为什么去掉后编译也通过了呢?请高手解释一下
a();
}private void c(){ //success
try{
a();
}catch(xxException ex){}
}private void d(){ //will not success
a();
}