Multiple catch Blocks


Multiple catch Blocks

If a try block contains code that can throw more than one type of exception object, (for example, DivideByZeroException as well as IndexOutOfRangeException), you can specify more than one catch block relating back to the same try block (as shown in Syntax Box 19.1). When an exception object is looking for a matching catch block, the possible catch blocks are inspected in the sequence in which they appear in the source code. The first matching catch block will handle the exception. After this matching catch block has been executed, all other related catch blocks are ignored, and the execution commences after the end of the last catch block.



When multiple catch blocks are applied, the exception subclasses specified for the catch block parameters must precede any of their base classes in the sequence of catch blocks. Otherwise, these subclass catch blocks become unreachable, which is invalid in C#. For example, the second catch block in the following lines of code contains the parameter exception class System.DivideByZeroException, which is a subclass of System.Exception the parameter class of the first catch block. As a result, any exception that is matched by System.DivideByZeroException is also matched by System.Exception. Consequently, the flow of execution will never reach the second catch block making the code invalid.



C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: