Library tutorials & articles

Exception Handling In C#

Try... Catch

Exceptions are handled by using try…catch statements. Code which may give rise to exceptions is enclosed in a try block , which is followed by one or more catch blocks. Well if we don't write like such we get errors like as follows :

class A {
 static void Main() {
  catch {
  }
 }
} 

TEMP.cs(3,5): error CS1003: Syntax error, 'try' expected 

class A {
 static void Main() {
  finally {
  }
 }
} 

TEMP.cs(3,5): error CS1003: Syntax error, 'try' expected 

class A {
 static void Main() {
  try {
  }
 }
} 
TEMP.cs(6,3): error CS1524: Expected catch or finally

The try block contains the code segment expected to raise an exception. This block is executed until an exception is thrown The catch block contains the exception handler. This block catches the exception and executes the code written in the block. If we do not know what kind of exception is going to be thrown we can simply omit the type of exception. We can collect it in Exception object as shown in the following program:

int a, b = 0 ;
Console.WriteLine( "My program starts " ) ;
try
{ 
 a = 10 / b; 
} 
catch ( Exception e )
{ 
 Console.WriteLine ( e ) ; 
} 
Console.WriteLine ( "Remaining program" ) ; 
The output of the program is:

My program starts
System.DivideByZeroException: Attempted to divide by zero.at ConsoleApplication4.Class1.Main(String[] args) in d:\dont delete\c#(c sharp)\swapna\programs\consoleapplication4\consoleapplication4\class1.cs:line 51
Remaining program

The exception 'Divide by zero' was caught, but the execution of the program did not stop.

Comments

  1. 27 Nov 2005 at 13:17

    Quote:
    [1]Posted by syedhara on 6 Aug 2002 05:03 PM[/1]
    This article has errors at the please don't publish articles with errors.
    Thanks
    Sri


    reinstall both os and software..and add urself in degbugger group

  2. 27 Nov 2005 at 13:16

    vxy

  3. 27 Nov 2005 at 13:16

    hi reinstall windows and remove and install .net and add urself in debugger gruops.

  4. 06 Aug 2002 at 17:03

    This article has errors at the please don't publish articles with errors.
    Thanks
    Sri

  5. 01 Jan 1999 at 00:00

    This thread is for discussions of Exception Handling In C#.

Leave a comment

Sign in or Join us (it's free).

Kamran Shakil I am 22 male. BS(Computer Science), MCSE, Brainbench certifed. Member of .NET Open source, Mono Project. E-author on various websites, including www.dotnetextreme.com, www.csharphelp.com and so on....
AddThis

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

Want to stay in touch with what's going on? Follow us on twitter!