1

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??

7
  • Put the try/catch around func2. Also why are you going through func1 to then call func2? Why not just call func2? Commented Jun 6, 2012 at 9:22
  • if no exception is explicitly thrown, how do you know func2 causes an exception? Commented Jun 6, 2012 at 9:22
  • Did you tried to throw an Exception explicitly from func2 ? Commented Jun 6, 2012 at 9:23
  • @BaliC this is obviously a sample. Commented Jun 6, 2012 at 9:25
  • In your example the exception is caught. There must be other problems in your code. Commented Jun 6, 2012 at 9:26

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

I have a question about this solution. From what i've learned i thought that if there was an exception in Func2 it would just die and end there. The way i have always done it is i would put a Try Catch around Func2 and Throw Exception in the catch. That way it would raise up to the next level which would be the Try where Func2 is called. There i would also Throw Exception which takes it up to where function 1 is called. Now it is at the top level and will do whatever code is in the catch in the func1 call. Can you explain how this works without throwing the exception? Thanks
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.