13.5 Catching generic exceptions


It may seem that a catch block specified with the System.Exception type (i.e. catch(System.Exception) ) can handle any type of exception object thrown, since all exception classes are subclasses of System.Exception . This is true only if the exception is thrown from C# code.

Since C# may work with other .NET languages (or even non- .NET languages, such as a COM object written in VB 6 or VC++ 6), it is possible that these codes might throw their own exception objects. And since they may not be .NET-compliant, it is possible that these exception objects are not subclasses of System.Exception . Under such circumstances, you can omit the exception type altogether after the catch keyword. Examine line 16 in this code fragment:

 10: try{ 11:   // method which invokes a legacy COM object 12: } 13: catch(Exception e){ 14:   Console.WriteLine("Object of type Exception caught"); 15: } 16:  catch{  17:   Console.WriteLine("Object of unknown type caught"); 18: } 

The exception handler from lines 16 “ 18 will be able to catch any type of exception object regardless of its type. You can't really do much exception handling with this type of catch block though, since the exception object caught is of an unknown type. Nevertheless, at least C# provides a way for you to deal with it.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net