Quiz #3

Take the following snippet:

public class Foo
{
  // add code
  public static int MethodOne() { return 0; }
  public static string MethodTwo() { return string.Empty; }
}

public class Program
{
  public static void Main()
  {
    try { Foo.MethodOne(); }
    catch (Exception ex) { Console.WriteLine(ex.Message); }

    try { Foo.MethodTwo(); }
    catch (Exception ex) { Console.WriteLine(ex.Message); }
  }
}

and add the code necessary (you cannot modify in any way MethodOne and MethodTwo) to make both method invocation throw an exception.

~ by Matteo on February 27, 2008.

8 Responses to “Quiz #3”

  1. public static void Main()
    {
    try {
    int i = Foo.MethodOne() / Foo.MethodOne();
    }
    catch (Exception ex) { Console.WriteLine(ex.Message); }

    try {
    int i = Foo.MethodTwo().Length / Foo.MethodOne();
    }
    catch (Exception ex) { Console.WriteLine(ex.Message); }
    }

    Is it correct ?

  2. No jude, you have to modify the Foo class, not the Main method…

  3. public class Foo
    {
    // add code
    public static int MethodOne() { return MethodOne(); }
    public static string MethodTwo() { return MethodTwo(); }
    }

    is it correct?

  4. no Marco, as I said in the post, you cannot modify in any way MethodOne and MethodTwo…

  5. public class Foo
    {
    public static int Value = Foo.MethodTwo().Length / Foo.MethodOne();

    public static int MethodOne() { return 0; }
    public static string MethodTwo() { return string.Empty; }
    }

  6. public class Foo {
    static Foo(){int i = 0 / MethodOne();}
    ~Foo(){}

    public static int MethodOne() { return 0; }
    public static string MethodTwo() { return string.Empty; }
    }

    this is my last answer matteo! both method invocation throw an exception.

  7. you’re almost right, but not totally. Your solution causes only one exception to be catched, not two. See the quiz: “add the code necessary [...] to make both method invocation throw an exception.”.

  8. Sorry, I didn’t see your last before replying. Yes, the exception thrown in the static constructor is the correct answer.

    Bravo!

Leave a Reply