C# try/catch

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.

Example

Without try/catch

snippet
using System;
public class ExExample
{
    public static void Main(string[] args)
    {
        int a = 10;
        int b = 0;
        int x = a/b;  
        Console.WriteLine("Rest of the code");
    }
}
Output
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
Example

C# try/catch example

snippet
using System;
public class ExExample
{
    public static void Main(string[] args)
    {
        try
        {
            int a = 10;
            int b = 0;
            int x = a / b;
        }
        catch (Exception e) { Console.WriteLine(e); }

        Console.WriteLine("Rest of the code");
    }
}
Output
System.DivideByZeroException: Attempted to divide by zero. Rest of the code
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +