Blog Stats
  • Posts - 24
  • Articles - 0
  • Comments - 61
  • Trackbacks - 92

 

C#: try..catch Usage

When catching an exception in C# you need not declare a variable for the exception instance if you do not need it.  This will avoid the “unused variable” warning. 

try { /* ... */ }
catch(Exception) // catches without assigning to a variable
{
    // ...
}

Here is how to rethrow an exception without affecting the stack trace:

try { /* ... */ }
catch(System.Data.SqlClient.SqlException ex)
{
    if(ex.Number==2627) { /* special case for primary key violation */ }
    else throw;   // rethrows without affecting the stack trace
    // else throw ex; // rethrows with the stack trace reset to this line
}

Feedback

# re: C#: try..catch Usage

Gravatar And, of course, you can go one stage further and use catch without declaring an Exception type.

try { /* ... */ }
catch
{
// ...
}

The compiler emits code to catch any type. I.e., the equivalent of:

try { /* ... */ }
catch (System.Object) // This is illegal syntax in C#
{
// ...
}

In the .NET framework, you can throw and catch objects of any type. However, C# imposes a language-specific rule that you can only throw System.Exception or derived types. In the same way, if you specify an exception type in a catch clause, this must be System.Exception or a derived class. However, for language operability purposes, you can catch any type using the syntax shown in the first examnple. 4/17/2004 6:11 PM | Charles Young

# re: C#: try..catch Usage

Gravatar Hmmm what is the syntax to catch a non-exception type and assign it to a variable? 4/17/2004 9:21 PM | Eron Wright

# re: C#: try..catch Usage

Gravatar Does it make any sense to write something like this (see below)?

int SomeFunct()
{
try {
SomeExceptionRaisingFunction();
}
catch {
throw;
}
}

The point of the question is whether in this case the try/catch with a simple rethrow would be redundant. 8/10/2004 3:24 AM | Vlad

# re: C#: try..catch Usage

Gravatar I think the statement has no effect whatsoever, and is likely ignored by the compiler. It won't cause a problem, though. Don't do it unless it is part of a pattern that you prefer. 8/10/2004 10:47 AM | Eron Wright

# re: C#: try..catch Usage

Gravatar catching and then throwing an exception would screw up your stack trace. If having code that doesn't do anything is part of the patern you prefer, you should rethink your prefered patern. It is redundant.

why would you want to catch a non-exception type? The whole try-catch model is for exceptions. if you are using it for return values, then you should rethink your design.

At least, that's my opinion on the matter. 9/25/2004 2:54 PM | Jason Hasner

# re: C#: try..catch Usage

Gravatar Both example affect the stack trace.

"throw ex;" destroys it completely, and resets it to the current line (just as if you created a brand new exception and threw that).

"throw;" is not as bad; it keeps any details of the stack below the current method, but replaces the last line (inside the try) with the one where it is rethrown. This could be an issue if you call the lower level function more than once.

"throw new MyException( ex );" will keep both the inner stack trace (with lines below the current method + the line in the current method where it emerged), as well as starting a new stack trace (from the throw line).
4/19/2005 11:15 PM | Stephen Gryphon

# re: C#: try..catch Usage

Gravatar Also, you may need to do some additional process (such as logging) if there is an error, but throw it for something else to actually handle. 10/4/2005 5:19 PM | Jarlezon

# re: C#: try..catch Usage

Gravatar hmm ... very good explanations on exception handing ever found...


thanks to all. 5/3/2006 3:44 AM | narendra

# re: C#: try..catch Usage

Gravatar <script language="javascript">alert('hello world'); </script> 5/3/2006 3:46 AM | ff

# re: C#: try..catch Usage

Gravatar Why should we throw exceptions in the catch block when we dont want to do anything with it. Should not we just let it propogate up? 7/13/2006 11:49 AM | Amardeep Dabass

# re: C#: try..catch Usage

Gravatar @Amardeep
because you may want to examine the exception, lets say thats thrown by your db, and then rethrow with a friendly message, unless it's something else then you let it bubble up
8/24/2006 7:52 AM | Dave

# re: C#: try..catch Usage

Gravatar does anyone know an easy way to "not try" a specific line of code within a try/catch?

for example, if you raise an event within a try/catch, and the event handler errors, your code catches it when you might not anticipate it, and your catch reacts as if your code errored.

For now, i have ended and started my try/catches around events, but it would be nice to have a trynot{} or untry{} option. 11/3/2006 9:06 PM | adam

# re: C#: try..catch Usage

Gravatar Hi,

If you throw without a parameter should preserve the complete stack trace and the exception information.

for example:

try
{
catch
// do some processing...
thow;
}

It seems the functionality of just using the throw without parameter is removed or a bug in newer versions. It no longer preserving the stack trace info. I saw this In .NET l.0 framework (VS.NET 2002).

9/21/2007 1:46 AM | Ashok

# re: C#: try..catch Usage , Throwing an Exception

Gravatar Throwing an Exception

In C#, it is possible to throw an exception programmatically. The ‘throw’ keyword is used for this purpose. The general form of throwing an exception is as follows.

throw exception_obj;

For example the following statement throw an ArgumentException explicitly.

throw new ArgumentException(“Exception”);

//C#: Exception Handling:
using System;
class MyClient
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception" );
}
Console.WriteLine("LAST STATEMENT");
}
}
9/28/2007 5:33 AM | Kishore Raavi

# re: C#: try..catch Usasge

Gravatar <script> type="text/javascript">location.href="http://www.google.com"; 12/13/2008 5:34 AM | ss

# re: C#: try..catch Usage

Gravatar Hi , This is

//C#: Exception Handling: Multiple catch
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ee)
{
Console.WriteLine("Exception" );
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}
2/12/2009 3:26 AM | Surendra Gurjar

# re: C#: try..catch Usage

Gravatar Hi , This is Surendra Gurjar

//C#: Exception Handling: Multiple catch
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ee)
{
Console.WriteLine("Exception" );
}
finally
{
Console.WriteLine("Finally Block");
}
Console.WriteLine("Result is {0}",div);
}
}
2/12/2009 3:27 AM | Surendra Gurjar

# female lesbian glammour models

Gravatar That is a really useful and informative guide. I’m going to try and keep a copy in my bag until i get used to what to watch out for.
lesbian domination videoshttp://lesbians.ifreepages.com/lesbian-domination-videos.html 8/23/2009 4:25 PM | Ignitte

# re: C#: try..catch Usage

Gravatar It was a very nice idea! 10/19/2009 10:11 PM | tiffany key ring

Post a comment





 

 

 

Copyright © Eron Wright