Labels

Monday, March 24, 2008

Catch All

Hi,

catch (Exception e)

{

Console.WriteLine( “An exception was thrown. Message was: “ + e.Message);

}

catch

{

Console.WriteLine(“Some other exception has occurred”); // Catch All Block

}

Note: catch (Exception e) will fire in case of .Net Exceptions and catch all fire in case of below mentioned case. There is no precedence concept here.

· This is the most general catch block of all—it doesn’t take any parameter.

· The reason this catch block is used is to catch exceptions thrown by other code that

o isn’t written in C#, or

o isn’t even managed code at all.

· It is a requirement of the C# language that only instances of classes that are derived from System.Exception can be thrown as exceptions, but other languages might not have this restriction— C++, for example, allows any variable whatsoever to be thrown as an exception.

· Although in many cases, the .NET PInvoke mechanism will trap these exceptions and convert them into .NET Exception objects, still if your code calls into libraries or assemblies that have been written in other languages, then it might find an exception thrown that is not derived from System.Exception. In such cases the catch all will work.

In an all, C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception.

Thanks & Regards,

Arun Manglick || Tech Lead

No comments:

Post a Comment