
- 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
try keyword in C#
A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
try { }
With that, you need to set catch statement as well to catch the exception −
try { // statements causing exception } catch( ExceptionName e1 ) { // error handling code }
The following is an example −
Example
class Demo { int result; Demo() { result = 0; } public void division(int val1, int val2) { try { result = val1 / val2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result: {0}", result); } } static void Main(string[] args) { Demo d = new Demo(); d.division(100, 0); Console.ReadKey(); } }
The above code snippet will throw an exception and it would be caught using catch −
Output
Exception caught: System.DivideByZeroException: Attempted to divide by zero. at Program.Demo.division (System.Int32 val1, System.Int32 val2) [0x00000] in <0d240b2120114744a121b66d65545f3f>:0 Result: 0
- Related Articles
- Try-Catch-Finally in C#
- try and except in Python
- Try-with-resources in Kotlin
- Can we declare a try catch block within another try catch block in Java?
- The try-finally Clause in Python
- try and except in Python Program
- Try, catch, throw and throws in Java
- What is the try block in Java?
- Try/catch/finally/throw keywords in C#
- What is try-with-resource in java?
- Explain Try/Catch/Finally block in PowerShell
- Static Keyword in C++
- “extern” keyword in C
- “register” keyword in C
- Restrict keyword in C

Advertisements