描述:
如果Java中的函数有可能抛出异常,则该异常要么被catch住,要么在声明函数时必须声明该函数体会throws exception。
处理的时候的流程是,当发生异常时,首先结束当前函数后续语句的执行,接着查看这个异常有无catch语句处理,如果没有则上浮至调用者。如果调用者没处理,继续上浮,直到处理位置,或者一直没处理则得到一条运行时错误并终止。如果在某一层被处理了,从catch语句开始继续执行。
代码实现:
package c04; import java.io.IOException; /** * @project: LearningJava * @filename: ExceptionTest.java * @version: 0.10 * @author: Jimmy Han * @date: 7:05 2015/8/23 * @comment: Test Purpose * @result: */ public class ExceptionTest { static void func1(){ System.out.println("enter func1"); try{ func2(); } catch(IOException e){ System.out.println("IOException handled in func1"); e.printStackTrace(System.err); } System.out.println("continue func1"); } static void func2() throws IOException{ System.out.println("enter func2"); func3(); System.out.println("continue func2"); } static void func3() throws IOException{ System.out.println("enter func3"); func4(); System.out.println("continue func3"); } static void func4() throws IOException{ System.out.println("enter func4"); throw new IOException(); //Never reach compile error //System.out.println("continue func4"); } static void func5(){ System.out.println("enter func5"); System.out.println("continue func5"); } public static void main(String[] args) { func1(); func5(); } }
输出:
java.io.IOException at c04.ExceptionTest.func4(ExceptionTest.java:38) at c04.ExceptionTest.func3(ExceptionTest.java:33) at c04.ExceptionTest.func2(ExceptionTest.java:28) at c04.ExceptionTest.func1(ExceptionTest.java:18) at c04.ExceptionTest.main(ExceptionTest.java:49) 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:483) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) enter func1 enter func2 enter func3 enter func4 IOException handled in func1 continue func1 enter func5 continue func5