
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to use Try/catch blocks in C#?
Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw.
try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
The following is an example showing how to use the try, catch, and finally in C#.
Example
using System; namespace Demo { class DivNumbers { int result; DivNumbers() { result = 0; } public void division(int num1, int num2) { try { result = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result); } } static void Main(string[] args) { DivNumbers d = new DivNumbers(); d.division(25, 0); Console.ReadKey(); } } }
Output
Result: 0
- Related Articles
- What are try, catch, finally blocks in Java?
- Can a try block have multiple catch blocks in Java?
- Can we define a try block with multiple catch blocks in Java?
- Try-Catch-Finally in C#
- Can we write any statements between try, catch and finally blocks in Java?
- How do we use try...catch...finally statement in JavaScript?
- Is it possible to have multiple try blocks with only one catch block in java?
- Try/catch/finally/throw keywords in C#
- Flow control in try catch finally in C#
- How to solve too many try catch in Typescript?
- Can we declare a try catch block within another try catch block in Java?
- What are unreachable catch blocks in Java?
- Nested try blocks in Exception Handling in Java
- Try, catch, throw and throws in Java
- Explain Try/Catch/Finally block in PowerShell

Advertisements