2016-10-14 81 views
-2

我想捕捉一个特定的异常并处理它,然后抛出一个执行代码来处理任何异常的泛型异常。这是如何完成的?这段代码不赶Exception等输出在catch块内抛出一个异常

Exception in thread "main" java.lang.Exception 
    at Main.main(Main.java:10) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:498) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) 
IOException specific handling 

Process finished with exit code 1 

的片段:

import java.io.IOException; 

public class Main { 

    public static void main(String[] args) throws Exception { 
     try { 
     throw new IOException(); 
     } catch (IOException re) { 
     System.out.println("IOException specific handling"); 
     throw new Exception(); 
     } catch (Exception e) { 
     System.out.println("Generic handling for IOException and all other exceptions"); 
     } 
    } 
} 
+4

可能的重复[异常抛出内部catch块 - 它会再次被捕获?](http://stackoverflow.com/questions/143622/exception-thrown-inside-catch-block-will-it-be-caught-再次) –

+0

这种失败的方式是什么?由于已经打印了“IOException特定处理”消息,因此您已到达“catch”块。然后,应用程序退出,出现异常,因为您*抛出异常*。 – David

+0

@David我希望执行Exception块中的代码。 – newToScala

回答

1

您在IOException异常的捕捉块抛出异常是从来没有抓到。这就是为什么你必须添加“抛出异常”到你的主要方法。

为了查找适合处理特定异常的catch-block,相同try之后的多个catch块的行为类似于if..else级联。

嵌入整个在try..catch在另一个try..catch块:

try { 
    try { 
    throw new IOException(); 
    } catch (IOException re) { 
    System.out.println("IOException specific handling"); 
    throw new Exception(); 
    } 
} catch (Exception e) { 
    System.out.println("Generic handling for IOException and all other xceptions"); 
    } 

通常一个嵌入原始异常在新通用的异常,让你在最后的异常处理不松动的信息(例如,如果要记录的堆栈跟踪,以确定确切位置异常发生):

throw new Exception(re); 

,并在决赛中捕捉块:

e.printStackTrace();