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.
-
- private void GetException(int param1, int param2)
- {
- try {
- var calculatedValue = param1 / param2;
- Console.WriteLine(calculatedValue);
- }
-
-
- }
- Multiple catch blocks can be followed a try block whereas multiple finally block throws compilation error.
- private void GetException(int param1, int param2)
- {
- try {
-
- } catch (ArgumentException argException) {
-
- } finally {
-
- } finally {}: Syntax error, 'try'
- expected
-
-
- }
- Catch block can’t be placed after finally block and it gives compile time error.
- private void GetException(int param1, int param2)
- {
- try {
-
- } finally {
-
- } catch (Exception ex) Syntax error, 'try'
- expected {
-
- }
-
-
- }
- 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.
- private void GetException(int param1, int param2 = 1) {
- try {
- var calculatedValue = param1 / param2;
- Console.WriteLine(calculatedValue);
- } catch (Exception ex) {
-
- } catch (ArgumentException argException) {
-
- }
- CS0160: A previous
- catch clause already catches all exceptions of this or of a super type('Exception')
-
-
- }
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.