Compilation Errors Using Try, Catch And Finally Keywords In C#

In C#, try, catch or finally keywords are used for an exception handling. However, these keywords should follow certain rules otherwise they throw compile time errors. Some scenarios are given below, which demonstrate what the scenarios are, which throw compilation errors are given below.

  • Try block must be followed by catch or finally block, else compile time error will come.
    1. //try ,catch and finally demo  
    2. private void GetException(int param1, int param2)  
    3. {  
    4.     try {  
    5.         var calculatedValue = param1 / param2;  
    6.         Console.WriteLine(calculatedValue);  
    7.     } //CS1524: Expected catch or finally  
    8.   
    9.   
    10. }  
  • Multiple catch blocks can be followed a try block whereas multiple finally block throws compilation error.
    1. private void GetException(int param1, int param2)   
    2. {  
    3.     try {  
    4.         //your code goes here  
    5.     } catch (ArgumentException argException) {  
    6.         //your code goes here   
    7.     } finally {  
    8.         //your code goes here  
    9.     } finally {}: Syntax error, 'try'  
    10.     expected  
    11.   
    12.   
    13. }  
  • Catch block can’t be placed after finally block and it gives compile time error.
    1. private void GetException(int param1, int param2)  
    2. {  
    3.     try {  
    4.         //your code goes here   
    5.     } finally {  
    6.         //your code goes here  
    7.     } catch (Exception ex) Syntax error, 'try'  
    8.     expected {  
    9.         //your code goes here  
    10.     }  
    11.   
    12.   
    13. }  
  • Catch block should follow order.

    Catch block should follow order, if catch block catches Base exception, it should be placed at the end of all the catch blocks, else the compiler will give compile time error, as shown below.

    Since base exception catches all the exception, rest of the catch blocks will never be executed.
    1. private void GetException(int param1, int param2 = 1) {  
    2.     try {  
    3.         var calculatedValue = param1 / param2;  
    4.         Console.WriteLine(calculatedValue);  
    5.     } catch (Exception ex) {  
    6.         //your code goes here   
    7.     } catch (ArgumentException argException) {  
    8.         //your code goes here   
    9.     }  
    10.     CS0160: A previous  
    11.     catch clause already catches all exceptions of this or of a super type('Exception')  
    12.   
    13.   
    14. }  

In some interview questions, you might have come across the scenarios shown above, so I believe this blog can help you answer those type questions.

Next Recommended Reading Impact of Try-Catch on Performance