C Sharp try/catch

C# try/catch

The try/catch statement is used in C# to perform exception handling. To place the code that may throw an exception, the try block is used in C# and to handle the exception, the catch block is used in C#. The try block must be placed before the catch block in C#.

Example: Without using try/catch:

using System;  
public class Example  
{  
    public static void Main(string[] args)  
    {  
        int X = 300;  
        int Y = 0;  
        int Z = X/Y;    
        Console.WriteLine("Hello World!!");  
    }  
}

Output:

Explanation:

In the above example, we are not using the try/catch statement and thus we are not handling the exception.

Example: Using try/catch:

using System;  
public class Example  
{  
    public static void Main(string[] args)  
    {  
        try {
        int X = 300;  
        int Y = 0;  
        int Z = X/Y; 
        }
 
        catch (Exception e) { Console.WriteLine(e); }  
        Console.WriteLine("Hello World!!");  
    }  
}

Output:

Explanation:

In the above example, we are using the try/catch statement and thus we are handling the exception. Here, the rest of the code is executed even after the exception.

Please follow and like us:
Content Protection by DMCA.com