2

Its been quite some time that I read about Exception filters in C# 6.0

I was to trying to use it in action. But not sure why I am getting the below error.

CS1003 Syntax error, 'when' expected C_6.0

This is how my snippet looks like

using System;
using static System.Console;

namespace C_6._0
{
public class Program
{
    static void Main(string[] args)
    {
        int val = 1;
        try
        {
            WriteLine("Enter value :");
            val = int.Parse(ReadLine());

        }
        catch (Exception ex) if (val == 0)
        {
            WriteLine("Input Invalid");
        }
        catch (Exception ex)
        {
            WriteLine(ex.Message);
        }
        ReadLine();
    }
 }}

I checked the version of C#, its 6.0 in my visual studio by

Properties -> Build -> Advanced Build Settings

Thanks.

6
  • What happens if you change if (val == 0) to when (val == 0)? Commented Sep 22, 2017 at 12:32
  • @mjwills, it builds but the links that I was referring shows to use if Commented Sep 22, 2017 at 12:35
  • 5
    Well, that page is wrong. Commented Sep 22, 2017 at 12:36
  • 4
    In early development of C# 6, it was if but they eventually changed it to when. Commented Sep 22, 2017 at 12:37
  • 2
    @Kgn-web it's better to read the docs than articles on various sites. Commented Sep 22, 2017 at 12:37

3 Answers 3

6

Many links online do show that the if should be correct but it is not true anymore. Syntax of the filtered exception is with when and not if:

try
{
    // Code here
}
catch (Exception ex) when (val == 0)
{
    WriteLine("Input Invalid");
}

See here on Official MSDN documentation


The article you commented is out of date. As mentioned by mjwills the reason is that in previous versions of the Visual Studio 2015 CTP, the if keyword was used instead of when.

Sign up to request clarification or add additional context in comments.

3 Comments

But all this links says about using if c-sharpcorner.com/UploadFile/7ca517/…
Cool.. Thanks :)
Also, it would be really great if you could please add just line to your post Note: In previous versions of the Visual Studio 2015 CTP, the if keyword was used instead of when.
2

Exception filtering used to use if (in CTP) but now uses when.

catch (Exception ex) when (val == 0)

This blog entry states:

Note: In previous versions of the Visual Studio 2015 CTP, the if keyword was used instead of when.

Comments

0

Use when instead of if

catch (Exception ex) when (val == 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.