.Net Framework
C# Tutorial
C# Control Statement
C# Arrays
C# Object Class
C# Properties
C# Inheritance
C# Polymorphism
C# Abstraction
C# Strings
C# Exception Handling
C# File IO
C# Collections
C# Generics
C# Delegates
C# Reflection
Anonymous Function
C# Multithreading
C# Synchronization
C# Web Service
C# Misc
C# New Features
C# Programs
C# Interview Questions
ADO.NET Tutorial
ASP.NET Tutorial
C# try/catch
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.
C# example without try/catch
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");
}
}
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.
C# try/catch example
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");
}
}
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
Rest of the code