Question regarding Try, Catch, Finally

I have some C# code in VS2010 that I've been working on. The code contains a Try, Catch, Finally block. When I test my code using the  Console.Writeline() method, I can see Exception error messages in the Output window, which can obviously be turned off if I don't want to display the exception messages.

So, my question is this...are those error messages the messages that are generated from my Catch block or are those exception error message in addition to the ones being trapped in my Catch block?

My concern is that the Try, Catch, Finally block is not trapping all the exceptions. If that were the case, would the application abort or would it just display error messages in the Output window?

I hope this question is not too confusing, but I'm a bit puzzled myself.

Thanks for your help,
Fulano
Mr_FulanoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ryan ChongCommented:
By default, Try... Catch will capture all the exceptions, but it also depends on what kind of exceptions you trying to "catch" with, such as IOException will only catch the exceptions relating to Input/Output operations, FileNotFoundException will only be able to handle a case when the file referring to is not found, etc.

to capture all the exceptions, you can try:
try
        {            
            // your codes here...
        }
        catch (Exception e)
 {
     // handle exception here...
}

Open in new window


try-catch (C# Reference)
https://msdn.microsoft.com/en-sg/library/0yd65esw.aspx

try-catch-finally (C# Reference)
https://msdn.microsoft.com/en-us/library/dszsf989.aspx
0
AndyAinscowFreelance programmer / ConsultantCommented:
>>from my Catch block or are those exception error message in addition to the ones being trapped in my Catch block?

They come from your WriteLine statement, in other words they come from where you code them to come from.
0
Athar SyedCommented:
In  a Try Catch ALL exceptions are caught. Except for cases where you do not put general Exception catcher. Let me explain...

The below code will throw the DivideByZero exception and it will be printed on the console screen.
int[] num = { 10, 20, 30 };
int div = 0;  // intentionally set to zero 
int result = 0;

try {
  for (int i = 0; i < 3; i++) {
    result = num[i] / div;
  }
} catch (DivideByZeroException ex) {
  Console.WriteLine("You cannot divide by Zero!");
} finally {
  Console.WriteLine("The result is {0}", result);
}

Open in new window


However, the below snippet will not throw any exception but crash & abort the application. That's because you did not handle the IndexOutOfRangeException in the catch.
int[] num = { 10, 20, 30 };
int div = 1;  // set as 1 to not give DivideByZero error
int result = 0;

try {
  // Looping 5 times will throw IndexOutOfRange error
  for (int i = 0; i < 5; i++) {
    result = num[i] / div;
  }
} catch (DivideByZeroException ex) {
  Console.WriteLine("You cannot divide by Zero!");
} finally {
  Console.WriteLine("The result is {0}", result);
}

Open in new window


And finally, the below will throw whatever error there can be on the console screen and dutifully continue to run the application.
int[] num = { 10, 20, 30 };
int div = 1;  // set as 1 to not give DivideByZero error
int result = 0;

try {
  // Looping 5 times will throw IndexOutOfRange error
  for (int i = 0; i < 5; i++) {
    result = num[i] / div;
  }
} catch (DivideByZeroException ex) {
  Console.WriteLine("You cannot divide by Zero!");
} catch (Exception ex) {
  Console.WriteLine("Something you were not expecting happened.");
  Console.WriteLine("The error is {0}", ex.Message);
} finally {
  Console.WriteLine("The result is {0}", result);
}

Open in new window


In conclusion, use the general Exception to catch any error. You can use specific exceptions to work around the application flow. The below snippet is a demo how specific error handling can be used to safely work through your application.
int[] num = { 10, 20, 30 };
int div = 0;
string result = string.Empty;
int count = 5;
bool bSuccess = false;

do {
  try {
    for (int i = 0; i < count; i++) {
      result += string.Format("{0} / {1} = {2}, ", num[1], div, num[i] / div);
    }
    bSuccess = true;
  } catch (IndexOutOfRangeException ex) {
    Console.WriteLine("You cannot go beyond the limits of an array! So now limiting to {0}.", num.Length);
    count = num.Length;    // limit to the size of the array
  } catch (DivideByZeroException ex) {
    Console.WriteLine("You cannot divide by Zero! So now dividing by 2.");
    div = 2;        // use a default value
  } catch (Exception ex) {
    Console.WriteLine("Something you were not expecting happened.");
    Console.WriteLine("The error is {0}", ex.Message);
  }
} while (!bSuccess);

Console.WriteLine(result);

Open in new window


Hope your puzzling confusion is solved! :)
1
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

käµfm³d 👽Commented:
@Andy

If they're in the Output window, then they might be First-Chance exceptions.
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AndyAinscowFreelance programmer / ConsultantCommented:
@kaufmed - good point, they never crossed my mind.
0
Mr_FulanoAuthor Commented:
All the responses were fantastic. -- I was able to get a complete solution to my question from both athar13 and from Kaufmed, who both did a great job of explaining the Try/Catch statement, and the "first chance" exceptions .... my exception messages are ALL "first chance" exceptions. (Please see below)

-- A first chance exception of type 'System.NullReferenceException' occurred in MetaDatareader_with_Loop.exe

-- A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

Per the link provided by Kaufmed, I now know the following:

"...For applications / components which handle exceptions gracefully, first chance exception messages let the developer know that an exceptional situation was encountered and was handled.'

From athar13's post, I now know that I can catch multiple exceptions, which I never knew!!! Very useful indeed.

Thank you both and I have split the points.

Fulano
0
Mr_FulanoAuthor Commented:
Excellent!!!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.