try keyword in C#


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

try {
}

With that, you need to set catch statement as well to catch the exception −

try {
      // statements causing exception
   } catch( ExceptionName e1 ) {
      // error handling code
   }

The following is an example −

Example

class Demo {
   int result;

   Demo() {
      result = 0;
   }

   public void division(int val1, int val2) {
      try {
         result = val1 / val2;
      } catch (DivideByZeroException e) {
         Console.WriteLine("Exception caught: {0}", e);
      } finally {
         Console.WriteLine("Result: {0}", result);
      }
   }

   static void Main(string[] args) {
      Demo d = new Demo();
      d.division(100, 0);
      Console.ReadKey();
   }
}

The above code snippet will throw an exception and it would be caught using catch −

Output

Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at Program.Demo.division (System.Int32 val1, System.Int32 val2) [0x00000] in <0d240b2120114744a121b66d65545f3f>:0
Result: 0

Updated on: 21-Jun-2020

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements