Definition - What does Catch Block mean?
A catch block, in C#, is an optional block of code that is executed when an exception is raised.
Catch block is a specific part of the exceptional handling construct, and is implemented using the "catch" keyword in combination with keywords "try" and "finally" and forms the means to implement structured exception handling. A try block includes the guarded code that can cause the exception. It encloses statements that deal with exceptional circumstances and works to recover from such unexpected conditions.
Catch block forms the means for handling exceptions. If these are not handled, this can lead to termination of the entire program by the .NET run time. A catch block can be used for handling any or specific exceptions.
Techopedia explains Catch Block
The exception handling model of Common Language Runtime (CLR) allows more than one catch block, each of which is designed to handle a specific exception. Whenever an exception occurs, the CLR looks for the catch block that handles the exception. If the currently executing method does not contain such a block, CLR searches for it in the method that called the current method up the call stack. If there is no matching clause found for that exception in the entire code, the execution of thread is stopped, and an unhandled exception message is displayed to the user.
The following are a few tips related to the use of a catch block:
- The exception type has to be specified to the catch block only after the reason behind the occurrence of specific unpreventable exceptions (like catastrophic system failure, API misuse, etc.) has been determined and recovery has been implemented without leaving the application in an inconsistent or invalid state.
- The catch block should be positioned so that the more specific exceptions have to be caught before the less specific ones.
- Catch block without parameters is referred as "eating exceptions" because this can suppress severe problems that are difficult to debug.
- Catch block can be centralized so that it can handle the exception from a central location.
- The "throw" statement can be used within catch block for which the same exception object passed in throw can be passed again while rethrowing.
- Variables declared within a try block cannot be used outside it.
- Code will not resume back to the try block after the catch block has been executed.
- Testing the exception handler code in catch block is essential to avoid breaking the application.
- Catch block should not be used for cleanup code.
- Catch block without parameters cannot be used for handling non-Common Language System-compliant exceptions (those not derived from System.Exception).