As we learned in the previous c# exception topic, exceptions are generated by CLR (common language runtime) or application code. To handle runtime or unexpected errors in applications, c# has provided a built-in exception handling support by using try, catch, and finally blocks.
In c#, when an exception is thrown, the CLR (common language runtime) will look for the
catch block that handles the exception. If the currently executing method does not contain such a
catch block, then the CLR will display an unhandled exception message to the user and stops the program's execution.
Following is the syntax of handling errors in c# using try, catch, and finally blocks.
As per the above syntax, the
try block will contain the guarded code that may cause an exception so that if any errors occurred in our code, then immediately the code execution will move to
catch block to handle those exceptions. In case, if no exception occurred in the
try block, then the
catch block will skip, and the execution will move to
After completion of
try & catch blocks, the
finally block will always execute even if an exception occurred or not, and it is useful to clean up or dispose of unmanaged objects based on the requirements.
In c#, the
try block must be followed by
finally or both blocks; otherwise, we will get a compile-time error. In a
try-catch-finally statement, only one
try & finally blocks are allowed, but we can use multiple
catch blocks to handle different exception types.
Following is the example of handling exceptions in c# using
If you observe the above code, we used a
finally blocks to handle runtime or unexpected errors during the execution of the program. Here, we wrote a code that may throw an exception inside of
try block, and in catch block, we are handling the exception. As discussed, the
finally block will execute after completion of
catch block execution.
When you execute the above code, you will get the result as shown below.
To know more in detail about exception handling in c#, check the following exception handling topics.
In c#, the
try-catch statement is useful to handle unexpected or runtime exceptions that will occur during the execution of the program.
To learn more about the try-catch statement, check the c# try-catch statement.
try-catch-finally is useful to handle unexpected exceptions in code. Here,
finally block is useful to clean up any resources that are allocated in the
To learn more about the try-catch-finally statement, then check the c# try-catch-finally statement.
throw keyword is useful to raise an exception manually, and it will throw all the exceptions which are derived from the
Exception base class.
To learn more about the throw keyword in c#, check the c# throw keyword.