package myExample.testException;public class TestException { public TestException() { } boolean testEx() throws Exception{ boolean ret = true; try{ ret = testEx1(); }catch (Exception e){ System.out.println("testEx, catch exception"); ret = false; throw e; }finally{ System.out.println("testEx, finally; return value="+ret); return ret; } } boolean testEx1() throws Exception{ boolean ret = true; try{ ret = testEx2(); if (!ret){ return false; } System.out.println("testEx1, at the end of try"); return ret; }catch (Exception e){ System.out.println("testEx1, catch exception"); ret = false; throw e; } finally{ System.out.println("testEx1, finally; return value="+ret); return ret; } } boolean testEx2() throws Exception{ boolean ret = true; try{ int b=12; int c; for (int i=2;i>=-2;i--){ c=b/i; System.out.println("i="+i); } return true; }catch (Exception e){ System.out.println("testEx2, catch exception"); ret = false; throw e; } finally{ System.out.println("testEx2, finally; return value="+ret); return ret; } } public static void main(String[] args) { TestException testException1 = new TestException(); try{ testException1.testEx(); }catch(Exception e){ e.printStackTrace(); } }}
输出System.out.println("testEx2, catch exception");
输出System.out.println("testEx2, finally; return value="+ret);
接下来 执行testEx1(),看到throws Exception
输出 System.out.println("testEx1, finally; return value="+ret);
然后返回上一层 执行testEx()看到throws Exception
输出System.out.println("testEx, finally; return value="+ret);
最后跳出到主函数
只要看到throws Exception 函数里面的try catch 就不执行,我这样理解对吗??
main函数是入口只要看到throws Exception 函数里面的try catch 就不执行,我这样理解对吗??----------
不是不执行try catch,而是执行,一旦有异常,就抛出了
{
try{ //在这里执行的代码有可能抛出
XXX1Exception,XXX2Exception,XXX3Exception,三种异常 }
catch (XXX1Exception e)
{
//如果try块中的代码抛出的异常是XXX1Exception这种异常,执行下面代码
}
catch (XXX2Exception e)
{
//如果try块中的代码抛出的异常是XXXException这种异常,执行下面代码
}
finally
{
//不管有没有异常,都执行下面的代码
}
说明(1)
//到这里,还有XXX3Exception这种异常没有被接住,在这里你可以不接,那么方法throws XXX3Exception这种异常给调用这个方法的方法来处理
}
{
try{ //假如:在这里执行的代码有可能抛出
XXX1Exception,XXX2Exception,XXX3Exception,三种异常 }
catch (XXX1Exception e) <----------------------
{ | (对应)
//如果try块中的代码抛出的异常是(XXX1Exception)..这种异常
执行下面代码
}
catch (XXX2Exception e) <----------------------
{ | (对应)
//如果try块中的代码抛出的异常是(XXX2Exception)这种异常,执行下面代码
}
finally
{
//不管有没有异常,都执行下面的代码
}
说明(1)
//到这里,还有XXX3Exception这种异常没有被接住,在这里你可以不接,那么方法throws XXX3Exception这种异常给调用这个方法的方法来处理
}
{ System.out.println("testEx, catch exception"); ret = false; throw e; }finally{ System.out.println("testEx, finally; return value="+ret); return ret; }
throw new Exception(); <---强制产生一个异常
}
catch (Exception e) <----既然后异常,就可以"抓住"
{ System.out.println("testEx, catch exception");<---就可以执行 ret = false; throw e; }finally{ System.out.println("testEx, finally; return value="+ret); return ret; }