HI WELCOME TO SIRIS

C# try/catch

Leave a Comment
In C# programming, exception handling is performed by try/catch statement. The try block in C# is used to place the code that may throw exception. The catch block is used to handled the exception. The catch block must be preceded by try block.

C# example without try/catch

  1. using System;  
  2. public class ExExample  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         int a = 10;  
  7.         int b = 0;  
  8.         int x = a/b;    
  9.         Console.WriteLine("Rest of the code");  
  10.     }  
  11. }  
Output:
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.

C# try/catch example

  1. using System;  
  2. public class ExExample  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         try  
  7.         {  
  8.             int a = 10;  
  9.             int b = 0;  
  10.             int x = a / b;  
  11.         }  
  12.         catch (Exception e) { Console.WriteLine(e); }  
  13.   
  14.         Console.WriteLine("Rest of the code");  
  15.     }  
  16. }  
Output:

System.DivideByZeroException: Attempted to divide by zero.
Rest of the code

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.