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 finally
block.
After completion of try
or 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 catch
or 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 try
, catch
and finally
blocks.
If you observe the above code, we used a try
, catch
and 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 try
or 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.
In c#, 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 try
block.
To learn more about the try-catch-finally statement, then check the c# try-catch-finally statement.
In c#, 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.