I suggest you ...

I wish catch multiple exceptions in the same catch

For example:

try
{
// smth}
catch (RemoteException, NamingException , CreateException e)
{
// smth
}

1,008 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Eric DelahayeEric Delahaye shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    34 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...
      • Corey MurtaghCorey Murtagh commented  ·   ·  Flag as inappropriate

        @shaihulud - The question remains as to whether this is an appropriate language construct to add to C#.

        VB.NET has a 'catch [exception object] when [condition]' which does filtering by properties of the exception object. Java has multiple exception type catches as suggested in this feature request.

        Neither of these are C#.

        Honestly, I have less of a problem with the VB.NET method, since it provides a far more flexible method for addressing the core issue without requiring a major change in the semantics of the language - which the Java method would require.

        Translating the VB.NET style of filtering to C# would require an adding a variant of the 'catch' keyword which takes a filtering statement similar to this:

        try
        {
        // exception thrown here
        }
        catch (SomeException e, e.SomeProperty > 0)
        {
        // process exception, only when e.SomeProperty > 0
        }
        catch (SomeException e, e.SomeProperty < 0)
        {
        // process exception, only when e.SomeProperty < 0
        }

        This functionality is a superset of the feature request, since it would include the ability to filter not only on the type of the exception, but on the properties of the exception object.

        However, this can already be achieved:

        try
        {
        // exception thrown here
        }
        catch (SomeException e)
        {
        if (e.SomeProperty > 0)
        {// do something }
        else if (e.SomeProperty < 0)
        { // do something else }
        else throw;
        }

        Not only is this functionally equivalent, it is a far simpler method to implement, and is conceptually simpler. It also makes it clear what is going to happen when something in your catch block throws an exception, which is not necessarily the case with a filter condition.

      • shaihuludshaihulud commented  ·   ·  Flag as inappropriate

        CLR already has an 'filter' support in try-catch-finnaly regions. Only required to extend С# syntax to support it.

        For an example:

        catch(Exception e) where Exception : OutOfMemoryException, NotImplementedException

      • Corey MurtaghCorey Murtagh commented  ·   ·  Flag as inappropriate

        This can already be achieved in C# by catching a common ancestor class (Exception) and testing the type of the caught exception. If you catch an exception that you are not expecting you can rethrow.

        try
        {
        // do something
        }
        catch (Exception e)
        {
        if (e as RemoteException == null && e as NamingException == null && e as CreateException == null)
        throw;
        // do something with RemoteException, NamingException or CreateException
        }

        The fact that Java supports such a construct has no bearing whatsoever on C#.

      • CyclopsCyclops commented  ·   ·  Flag as inappropriate

        An interesting idea, however, each exception would need its own unique name, as exceptions can include additional properties. Alternatively, capture the basic Exception as e and cast it to the types you require, using the as operator, example:

        var re = e as RemoteException;

      • Fox GlacierFox Glacier commented  ·   ·  Flag as inappropriate

        It is stated by multiple commenters that this should be considered because Java has it. There's a reason Java has it, Java supports intersection types. This doesn't exist in C#. It's the same reason why determining the type of a conditional expression is straightforward in C# and a ponderous undertaking in Java. It's possible that C# does have intersection types and I just don't understand, but if it doesn't (as I suspect) the C# language misses the fundamental building blocks to make this possible. Which isn't necessarily a bad thing, IMO.

      • John SaundersJohn Saunders commented  ·   ·  Flag as inappropriate

        Very bad idea, in general. There should be very little code in a typical application that catches exceptions, and that code should be catching and handling the most specific exception possible.

        Most code I've seen that catches exceptions should really not be catching them at all.

      • Victor ZakharovVictor Zakharov commented  ·   ·  Flag as inappropriate

        This would be a useless feature - don't spend any effort there, as there are much more important things to consider. All those exceptions can have different types, so they provide different set of properties. You cannot organize them all under variable e. It's like you want your car to be your wife and your can of beer.

      • PhilippePhilippe commented  ·   ·  Flag as inappropriate

        Seriously, that feature does not make much sense in my opinion as in a properly designed application there should not that much catch clause in an application.

        And if you want to do some general exception handling, it does not make much sense to repeat the same code at a lot of place.

        If is very easy to create an helper class that would have functions to execute commonly uses code.

        As an example:
        public static class ExceptionHelper
        {
        void LogException(Exception x)
        {
        var xAsArgNullException = x as ArgumentNullExpection;
        if (x != null)
        {
        logger.WriteLine("Null exception catched");
        }
        }

        void DoStandardProcessing(Exception x)
        {
        if (some_condition)
        {
        // Rethrow any exception we do not consider handled.....
        throw;
        }
        }
        }

      • MonomachusMonomachus commented  ·   ·  Flag as inappropriate

        AFAIK Java 7 has that possibility too. I honestly think this is the only better language feature than in C#/.NET. We should make that too.

      • AnonymousAnonymous commented  ·   ·  Flag as inappropriate

        Can't you just do a catch-all and then switch on the type of e and rethrow if unknown?

      • chrischris commented  ·   ·  Flag as inappropriate

        So then e is of type what?

        do this:
        try
        {
        // CODE
        }
        catch (Exception ex)
        {
        var acceptTypes = new[] {
        typeof(InvalidCastException),
        typeof(StackOverflowException),
        typeof(DivideByZeroException),
        };

        if (!acceptTypes.Contains(ex.GetType()))
        {
        throw;
        }
        // process combined exception
        }

      • Adam RalphAdam Ralph commented  ·   ·  Flag as inappropriate

        As with far too many other ideas posted on this site, this is not an idea for the Visual Studio IDE. It is an idea for C# and ultimately would need to be implemented in the C# compiler. Yes, Visual Studio would then have to support it, but this is purely a automatic knock on requirement of any change to the C# compiler.

        There doesn't seem to be any place for general comments about the site which is why I'm writing this comment against this idea, which seems to be the currently highest voted non-VS idea.

        I think this site is a great idea but It would be good if the site owners (or those with appropriate permissions) could review the ideas, specially the high voted ones, and migrate them to a more appropriate site if necessary. For example, this idea should be migrated to csharp.uservoice.com (which would need to be created first). It would also be good if some more explicit guidelines could be added regarding what kind of ideas should be posted on this site. This would help to avoid the accumulation of yet more ideas about compilers and frameworks instead of ideas about the VS IDE.

      • Staffan EketorpStaffan Eketorp commented  ·   ·  Flag as inappropriate

        Actually - it would be nice to introduce a syntax on "type combinations", i.e. something like

        try {...}
        catch(ExceptionA || ExceptionB || ExceptionC) {....}

        This would then resolve down to the last common denominator of those types. Another use of this principle would be to use something like && combinators to indicate the guarantee that some object fullfils multiple type contracts

      • CarstenCarsten commented  ·   ·  Flag as inappropriate

        Why not stack the catches? Well, honestly, why catching exceptions at all? There is roughly NO reason to catch exceptions at all, "roughly no" meaning zero plusminus one. Those very few occasions you really need to catch an exception because there is exactly NO way to foresee the advent of it, well: stack them. In any other case, just armor your application.

      • sbisbi commented  ·   ·  Flag as inappropriate

        This is a good example for why we need to be able to downvote suggestions, too.

      ← Previous 1

      Feedback and Knowledge Base