Here there are certain syntactical combinations of try catch finally blocks. At the end of every block we have commented wheather it is correct or compilation error.
Example 01
1 2 3 4 5 6 7 8 9 |
try{ } catch (Exception e){ } //correct |
Example 02
1 2 3 4 5 6 7 8 9 10 |
try{ }catch (X e) { }catch (Y e) { } //correct (X is Child class Y is super Exception class) |
Example 03
1 2 3 4 5 6 7 8 9 10 11 |
try{ }catch (X e) { }catch (X e) { } //X is some Exception class name //Compilation Error : exception X has already been caught |
Example 04
1 2 3 4 5 6 |
try{ } //Compilation Error: try with out catch or finally |
Example 05
1 2 3 4 5 6 |
catch (Exception e) { } //Compilation Error: catch without try |
Example 06
1 2 3 4 5 6 7 8 9 10 |
try{ } System.out.println("hi"); catch (Exception e) { } //Compilation Error 1: try without catch or finally //Compilation Error 2: catch without try |
Example 07
1 2 3 4 5 6 7 8 9 10 11 |
try{ }catch (Exception e) { } finally{ } //correct |
Example 08
1 2 3 4 5 6 7 8 |
try{ }finally{ } //correct |
Example 09
1 2 3 4 5 6 7 8 9 10 11 |
try{ } finally{ } finally{ } //Compilation Error: finally with out try |
Example 10
1 2 3 4 5 6 7 8 9 10 11 12 13 |
try{ }catch (Exception e) { } System.out.println ("hi"); finally{ } //Compilation Error: finally without try |
Example 11
1 2 3 4 5 6 7 8 9 10 11 |
try{ }finally{ } catch (Exception e) { } //Compilation Error: catch without try |
Example 12
1 2 3 4 5 6 |
finally{ } //Compilation Error: finally without try |
Example 13
1 2 3 4 5 6 7 8 9 10 11 |
try{ try{ }catch (Exception e) { } }catch (Exception e) { } //correct |
Example 14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
try{ }catch (Exception e) { try{ } finally{ } } //correct |
Example 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
try{ }catch (Exception e){ try{ }catch (Exception e) { } }finally{ } //correct |
Example 16
1 2 3 4 5 6 7 8 9 10 |
finally{ } try{ }catch (Exception e) { } //Compilation Error: finally without try |
Example 17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
try{ }catch (Exception e) { }finally{ try{ }catch (Exception e) { } } //correct |
Example 18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
try { try { } catch (Exception e) { } finally { } } catch (Exception e) { try { } catch (Exception e1) { } finally { } } finally { try { } catch (Exception e) { } finally { } } // correct |