Try/catch/finally/throw keywords in C#

Exception handling is based on the following keywords and its usage −

  • try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.

  • catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

  • finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

  • throw − A program throws an exception when a problem shows up. This is done using a throw keyword.

To handle exceptions, you need to set them like the following syntax in C# −

try {
   // statements causing exception
} catch( ExceptionName e1 ) {
   // error handling code
} catch( ExceptionName e2 ) {
   // error handling code
} catch( ExceptionName eN ) {
   // error handling code
} finally {
   // statements to be executed

Updated on: 20-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started