Creating Dedicated catch Statements
So far, you’ve been working with generic catch statements only. You can create dedicated catch statements that handle only some exceptions and not others, based on the type of exception thrown. Example 16-4 illustrates how to specify which exception you’d like to handle. This example performs some simple division. As you’d expect, dividing by zero is illegal, and C# has a specific exception just for that. For the purposes of demonstration, we’ll say that the dividend in the operation also cannot be zero. Mathematically, that’s perfectly legal, but we’ll assume that a result of zero would cause problems elsewhere in the program. Obviously, C# doesn’t have an exception type for that, so we’ll use a more general exception for that case.
Example 16-4. Each of these three dedicated catch statements is intended for a different type of exception
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_16_4_ _ _ _Dedicated_catch_Statements { class Tester { public void Run() { try { double a = 5; double b = 7; Console.WriteLine("Dividing {0} by {1}...", a, b); Console.WriteLine("{0} / {1} = {2}", a, b, DoDivide(a, b)); } // most specific exception type first catch (DivideByZeroException) { Console.WriteLine("DivideByZeroException caught!"); } catch (ArithmeticException) { Console.WriteLine("ArithmeticException caught!"); } // generic exception type last catch { Console.WriteLine("Unknown exception caught"); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access