In the C# try and catch statement allows to define a block of c# programming code to be tested for errors while it is being executed. try-catch statement in C# is used in to find exceptions and try to solve or manage to error log.
The catch block is used to handled the exception and try block in C# is used to place the c# programming code that may throw exception.
C# example without try/catch
using System;
public class ExExample
{
public static void Main(string[] args)
{
int firstNumber = 10;
int secondNumber = 0;
int result = firstNumber/secondNumber;
Console.WriteLine("Manage the c# code");
}
}
Output
Run-time exception (line 9): Attempted to divide by zero.
Stack Trace:[System.DivideByZeroException: Attempted to divide by zero.]
at ExExample.Main(String[] args) :line 9
C# try/catch example
using System;
public class ExExample
{
public static void Main(string[] args)
{
try{
int firstNumber = 10;
int secondNumber = 0;
int result = firstNumber/secondNumber;
Console.WriteLine("Manage the c# code");
}
catch(Exception e){
Console.WriteLine(e);
}
}
}
Output
System.DivideByZeroException: Attempted to divide by zero.
at ExExample.Main(String[] args) in d:\Windows\Temp\pnm1k0o0.0.cs:line 10