{"id":204,"date":"2012-12-01T10:13:29","date_gmt":"2012-12-01T09:13:29","guid":{"rendered":"http:\/\/benjiweber.co.uk\/blog\/?p=204"},"modified":"2012-12-01T10:17:50","modified_gmt":"2012-12-01T09:17:50","slug":"multicatch-in-c-and-old-java","status":"publish","type":"post","link":"https:\/\/benjiweber.co.uk\/blog\/2012\/12\/01\/multicatch-in-c-and-old-java\/","title":{"rendered":"MultiCatch in c# and old java"},"content":{"rendered":"<p class=\"lead\">Someone on IRC was asking whether it was possible to do catch multiple types of exceptions at the same time in c#.<\/p>\n<p>In Java 7 there&#8217;s a feature from <a href=\"http:\/\/openjdk.java.net\/projects\/coin\/\">project coin<\/a> called multi catch that enables the following syntax:<\/p>\n<pre lang=\"java\">\r\npublic class MultiCatch {\r\n\tpublic static void main(String... args) {\r\n\t\ttry {\r\n\t\t\tthrow new ExceptionA();\t\r\n\t\t} catch (final ExceptionA | ExceptionB ex) {\r\n\t\t\tSystem.out.println(\"Got \" + ex.getClass().getSimpleName());\r\n\t\t}\r\n\t}\r\n}\r\n\r\nclass ExceptionA extends RuntimeException {}\r\nclass ExceptionB extends RuntimeException {}\r\n<\/pre>\n<p>Here the catch block catches either an ExceptionA or an ExceptionB. This can be useful if you want to handle several exceptions in the same way.<\/p>\n<p>I don&#8217;t believe c# has a similar language feature, however since it has lambdas you can replicate something similar yourself like so:<\/p>\n<pre lang=\"java\">\r\nusing System;\r\n\r\npublic class MultiCatch {\r\n  public static void Main() {\r\n    Trier.Try(() => {\r\n      throw new ExceptionA(\" Hello A\");\r\n    }).Catch<ExceptionA, ExceptionB>(ex => {\r\n      Console.WriteLine(ex.GetType() + ex.Message);\r\n    });\r\n\r\n    Trier.Try(() => {\r\n      throw new ExceptionC(\" Hello C\");\r\n    }).Catch<ExceptionA, ExceptionB, ExceptionC>(ex => {\r\n      Console.WriteLine(ex.GetType() + ex.Message);\r\n    });\r\n  }\r\n}\r\n\r\n<\/pre>\n<p>We create a method called Try and pass it an Action. We then chain a call to a Catch method which we pass the Exceptions we want to catch as Type arguments. As you can see we can vary the number of type arguments. This is something you can&#8217;t do in Java partly due to type erasure.<\/p>\n<p>The Try method simply passes the action through to a Catcher<\/p>\n<pre lang=\"java\">\r\n  public static Catcher Try(Action action) {\r\n    return new Catcher(action);\r\n  }\r\n<\/pre>\n<p>and the Catch method has overloads for any number of exceptions you want to support. We can restrict the type arguments to only Exception types by using the where clause.<\/p>\n<pre lang=\"java\">\r\n  public void Catch<T,U>(Action<Exception> catchAction) where T : Exception where U : Exception {\r\n    try {\r\n      action();\r\n    } catch (T t) {\r\n      catchAction(t);\r\n    } catch (U u) {\r\n      catchAction(u);\r\n    }\r\n  }\r\n<\/pre>\n<p>Here&#8217;s the full code listing:<\/p>\n<pre lang=\"java\">\r\nusing System;\r\n\r\npublic class MultiCatch {\r\n  public static void Main() {\r\n    Trier.Try(() => {\r\n      throw new ExceptionA(\" Hello A\");\r\n    }).Catch<ExceptionA, ExceptionB>(ex => {\r\n      Console.WriteLine(ex.GetType() + ex.Message);\r\n    });\r\n\r\n    Trier.Try(() => {\r\n      throw new ExceptionC(\" Hello C\");\r\n    }).Catch<ExceptionA, ExceptionB, ExceptionC>(ex => {\r\n      Console.WriteLine(ex.GetType() + ex.Message);\r\n    });\r\n  }\r\n}\r\n\r\nclass Trier {\r\n  public static Catcher Try(Action action) {\r\n    return new Catcher(action);\r\n  }\r\n}\r\n\r\nclass Catcher {\r\n  private Action action;\r\n  public Catcher(Action action) {\r\n    this.action = action;\r\n  }\r\n\r\n  public void Catch<T,U>(Action<Exception> catchAction) where T : Exception where U : Exception {\r\n    try {\r\n      action();\r\n    } catch (T t) {\r\n      catchAction(t);\r\n    } catch (U u) {\r\n      catchAction(u);\r\n    }\r\n  }\r\n  \r\n   public void Catch<T,U,V>(Action<Exception> catchAction) where T : Exception where U : Exception where V : Exception {\r\n    try {\r\n      action();\r\n    } catch (T t) {\r\n      catchAction(t);\r\n    } catch (U u) {\r\n      catchAction(u);\r\n    } catch (V v) {\r\n      catchAction(v);\r\n    }\r\n  }\r\n}\r\n\r\nclass ExceptionA : Exception {\r\n  public ExceptionA(string message) : base(message) {}\r\n}\r\n\r\nclass ExceptionB : Exception {\r\n  public ExceptionB(string message) : base(message) {}\r\n}\r\n\r\nclass ExceptionC : Exception {\r\n  public ExceptionC(string message) : base(message) {}\r\n}\r\n\r\n<\/pre>\n<p>This is why Java needs lambdas. Because they fix everything \u00ac_\u00ac<\/p>\n<p>For reference, the closest I could do in Java prior to 7 was something like this:<\/p>\n<pre lang=\"java\">\r\npublic class MultiCatchWithoutCoin {\r\n\tpublic static void main(String... args) {\r\n\t\tnew TrierII<ExceptionA, ExceptionB>() {\r\n\t\t\tpublic void Try() {\r\n\t\t\t\tthrow new ExceptionA();\r\n\t\t\t}\r\n\t\t\tpublic void Catch(Exception ex) {\r\n\t\t\t\tSystem.out.println(\"Got \" + ex.getClass().getSimpleName());\r\n\t\t\t}\r\n\t\t};\r\n\t}\r\n}\r\n<\/pre>\n<p>I had to use an abstract class instead of lambdas as Java has no lambdas. I also had to create a new class for each number of type arguments I wanted because you can&#8217;t overload with variable numbers of type arguments.<\/p>\n<p>I also had to use <a href=\"http:\/\/gafter.blogspot.co.uk\/2006\/12\/super-type-tokens.html\">Gafter&#8217;s gadget<\/a> to access the types of the Exceptions to catch.<\/p>\n<p>Here&#8217;s the full code listing. <\/p>\n<pre lang=\"java\">\r\nimport java.lang.reflect.InvocationTargetException;\r\nimport java.lang.reflect.ParameterizedType;\r\nimport java.lang.reflect.Type;\r\nimport java.util.ArrayList;\r\n\r\npublic class MultiCatchWithoutCoin {\r\n\tpublic static void main(String... args) {\r\n\t\tnew TrierII<ExceptionA, ExceptionB>() {\r\n\t\t\tpublic void Try() {\r\n\t\t\t\tthrow new ExceptionA();\r\n\t\t\t}\r\n\t\t\tpublic void Catch(Exception ex) {\r\n\t\t\t\tSystem.out.println(\"Got \" + ex.getClass().getSimpleName());\r\n\t\t\t}\r\n\t\t};\r\n\t}\r\n}\r\n\r\nabstract class TrierII<T extends Exception, U extends Exception> {\r\n\tpublic abstract void Try();\r\n\tpublic abstract void Catch(Exception ex);\r\n\tpublic TrierII() throws T, U {\r\n\t\ttry {\r\n\t\t\tTry();\t\r\n\t\t} catch (Exception e) {\r\n\t\t\tif (getTypeArgument(1).isAssignableFrom(e.getClass()) || getTypeArgument(2).isAssignableFrom(e.getClass())) { \r\n\t\t\t\tCatch(e);\r\n\t\t\t}\r\n\t\t\tthrow e;\r\n\t\t} \r\n\t}\r\n\t\r\n\tClass<? extends Exception> getTypeArgument(int num) {\r\n\t\tType superclass = getClass().getGenericSuperclass();\r\n\t\tif (superclass instanceof Class) {\r\n\t\t\tthrow new RuntimeException(\"Missing type parameter.\");\r\n        \t}\r\n        \tType type = ((ParameterizedType) superclass).getActualTypeArguments()[num - 1];\r\n\t\tif (type instanceof Class<?>) {\r\n               \t\treturn (Class<? extends Exception>) type;\r\n\t\t} else {\r\n\t\t\treturn (Class<? extends Exception>) ((ParameterizedType) type).getRawType();\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\nclass ExceptionA extends RuntimeException {}\r\nclass ExceptionB extends RuntimeException {}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Someone on IRC was asking whether it was possible to do catch multiple types of exceptions at the same time in c#. In Java 7 there&#8217;s a feature from project coin called multi catch that enables the following syntax: public class MultiCatch { public static void main(String&#8230; args) { try { throw new ExceptionA(); }&#8230;  <a href=\"https:\/\/benjiweber.co.uk\/blog\/2012\/12\/01\/multicatch-in-c-and-old-java\/\" class=\"more-link\" title=\"Read MultiCatch in c# and old java\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[25,8],"tags":[12,23],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v14.9 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/benjiweber.co.uk\/blog\/2012\/12\/01\/multicatch-in-c-and-old-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"MultiCatch in c# and old java - Benji&#039;s Blog\" \/>\n<meta property=\"og:description\" content=\"Someone on IRC was asking whether it was possible to do catch multiple types of exceptions at the same time in c#. In Java 7 there&#8217;s a feature from project coin called multi catch that enables the following syntax: public class MultiCatch { public static void main(String... args) { try { throw new ExceptionA(); }... Read more &raquo;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/benjiweber.co.uk\/blog\/2012\/12\/01\/multicatch-in-c-and-old-java\/\" \/>\n<meta property=\"og:site_name\" content=\"Benji&#039;s Blog\" \/>\n<meta property=\"article:published_time\" content=\"2012-12-01T09:13:29+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2012-12-01T09:17:50+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#website\",\"url\":\"https:\/\/benjiweber.co.uk\/blog\/\",\"name\":\"Benji&#039;s Blog\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/benjiweber.co.uk\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/2012\/12\/01\/multicatch-in-c-and-old-java\/#webpage\",\"url\":\"https:\/\/benjiweber.co.uk\/blog\/2012\/12\/01\/multicatch-in-c-and-old-java\/\",\"name\":\"MultiCatch in c# and old java - Benji&#039;s Blog\",\"isPartOf\":{\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#website\"},\"datePublished\":\"2012-12-01T09:13:29+00:00\",\"dateModified\":\"2012-12-01T09:17:50+00:00\",\"author\":{\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/benjiweber.co.uk\/blog\/2012\/12\/01\/multicatch-in-c-and-old-java\/\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09\",\"name\":\"benji\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/05fb47b31a0b329e1b790074a9b624ef?s=96&d=mm&r=g\",\"caption\":\"benji\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","amp_enabled":true,"_links":{"self":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/204"}],"collection":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/comments?post=204"}],"version-history":[{"count":7,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/204\/revisions"}],"predecessor-version":[{"id":211,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/204\/revisions\/211"}],"wp:attachment":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=204"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=204"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=204"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}