Free mag vol1 | Page 336

CHAPTER 7  UNDERSTANDING STRUCTURED EXCEPTION HANDLING General catch Statements C# also supports a “general” catch scope that does not explicitly receive the exception object thrown by a given member: // A generic catch. static void Main(string[] args) { Console.WriteLine("***** Handling Multiple Exceptions *****\n"); Car myCar = new Car("Rusty", 90); try { myCar.Accelerate(90); } catch { Console.WriteLine("Something bad happened..."); } Console.ReadLine(); } Obviously, this is not the most informative way to handle exceptions, since you have no way to obtain meaningful data about the error that occurred (such as the method name, call stack, or custom message). Nevertheless, C# does allow for such a construct, which can be helpful when you want to handle all errors in a very, very general fashion. Rethrowing Exceptions When you catch an exception, it is permissible for the logic in a try block to rethrow the exception up the call stack to the previous caller. To do so, simply use the throw keyword within a catch block. This passes the exception up the chain of calling logic, which can be helpful if your catch block is only able to partially handle the error at hand: // Passing the buck. static void Main(string[] args) { ... try { // Speed up car logic... } catch(CarIsDeadException e) { // Do any partial processing of this error and pass the buck. throw; } ... } Be aware that in this example code, the ultimate receiver of CarIsDeadException is the CLR, because it is the Main() method rethrowing the exception. Because of this, your end user is presented with a 274