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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.80.34