intrigued_66
intrigued_66

Reputation: 17220

Exception not throwing?

I have code resembling the following:

try{
    func1();
}
catch(Exception e){
    /Do something
}


static func1(){
    func2();
}

static func2(){
    //Exception thrown here
    System.IO.StreamReader file = new System.IO.StreamReader(filePath);
}

when an exception is thrown by the line of code in func2() I get no notification in the catch clause. I do not explicitly throw anything, I just have regular function declarations which are static- no "throw" appears anywhere.

Why isn't the exception propagating upwards to the catch statement??

Upvotes: 1

Views: 149

Answers (2)

Rob P.
Rob P.

Reputation: 15071

An exception will 'bubble up' until it is caught or crashes your app.

Your best bet is to use the Debugger. Make sure you have it set to stop on HANDLED exceptions (Debug / Exceptions / Check the 'Thrown' box on the Common Language Runtime Exceptions).

Now run your code. If func2 throws an exception - your code will break; regardless of whether or not it is handled. You can step through the code and see what is handling it.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062510

No, the code is fine. There is something in your real code that you aren't showing us. That exception propagates fine:

using System;

static class Program {
    static void Main() {
        try{
            func1();
        } catch(Exception e) {
            // works fine: FileNotFoundException
            Console.WriteLine(e);
        }
    }
    static void func1(){
        func2();
    }    
    static void func2() {
        string filePath = "doesnot.exist";
        System.IO.StreamReader file = new System.IO.StreamReader(filePath);
    }
}

Candidates:

  • anything involving a try is suspect - treble check it
  • anything involving threading may have the exception somewhere else

Upvotes: 6

Related Questions