前言
一直对异常捕捉都是e.printStackTrace()
就完事了, 突然对异常捕捉顺序很好奇, 就做了个测试, 直接看代码。
从小到大捕捉
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class MyTest { @Test public void test(){ try{ throw new FileNotFoundException("文件没找到"); } catch (FileNotFoundException e){ System.out.println("FileNotFoundException "); } catch (IOException e){ System.out.println("IOException"); } catch (Exception e){ System.out.println("Exception "); } catch (Throwable e){ System.out.println("Throwable "); } } }
|
从大到小捕捉
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class MyTest { @Test public void test(){ try{ throw new FileNotFoundException("文件没找到"); } catch (Throwable e){ System.out.println("Throwable "); } catch (FileNotFoundException e){ System.out.println("FileNotFoundException "); } catch (IOException e){ System.out.println("IOException"); } catch (Exception e){ System.out.println("Exception "); } } }
|
结论
Java异常捕捉顺序是
- 从上到下
- 从小到大