![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements