Error catching in C#

Hi,

How can I catch error's from the objSession and the objAccount in the following C# code?

If they return an error when I run it with debugger, the Locals window shows me which of them are wrong with red text, how can I trap this in an error message instead of application crash?


Thanks for reading :-)
private void btnTest_Click (object sender, EventArgs e)
{
   string sTApp = "app";
   string sTKey = "key";
   string sUserName = "user";
   string sPassword = null;
   string sCmdLine = "";
   string sReserved = "";
 
 
   comdll.application newapp = new comdll.application();
   objSession = newapp.session(sTApp, sTKey);
   objAccount = objSession.Account(sUserName, sCmdLine, sPassword, sReserved);
   MessageBox.Show(objAccount.Owner.LastName);
}

Open in new window

LVL 2
TheFlyingCorpseAsked:
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.

abelCommented:
You can add a try/catch around it. That's the C# way of catching errors. The try-block says "try this code, it may contain errors". The catch-block says "catch this or that error, but if I cannot catch you, i.e., if you do not specify the right error, then I'll just throw the error uncaught".

The catch block is the most tricky part. You can have as many as you wish and they must be in the order of most specific to most generic. If your error (which always inherits from Exception) is castable to one of the exceptions in the throw block, the code will continue in the throw block the minute an exception is thrown. The below code will catch every possible exception:

try {
   objSession = newapp.session(sTApp, sTKey);
catch(Exception e) {
   MessageBox.Show("error in objSession: " + e.Message);
}
 
try {
   objAccount = objSession.Account(sUserName, sCmdLine, sPassword, sReserved);
} catch (Exception e) {
   MessageBox.Show("error in objAccount: " + e.Message);
}

Open in new window

0
abelCommented:
There's a missing closing accolade in line three (below are the first three lines corrected). If you want to see more of the exception information, you can place a breakpoint in the catch block (line 4 and 10) and hover over the exception.

You can be more specific by saying, for instance: catch(NullReferenceException e). To find out what exceptions are thrown, start out with the generic one and investigate the exceptions being thrown (or just let throw in the debugger and review the information that the debugger shows you, i.e., it will show the type of the exception).

try {
   objSession = newapp.session(sTApp, sTKey);
} catch(Exception e) {

Open in new window

0
TheFlyingCorpseAuthor Commented:
Ok,

How can I catch exceptions in arguments that are invalid? The debugger marks them as red, but the error message does not reflect this.
(And the script continues generating several more errors, need to add a breakpoint here.)


Thx so far tho =)
0
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

abelCommented:
You cannot "catch" exceptions that are already caught by the debugger. The reason is: these are different types of exceptions, these are called compile-time exceptions, versus runtime exceptions otherwise. Compile time exceptions, as the name suggest, occur while you are typing or when you click Project > Compile. Any compile time exception MUST be solved before you can actually compile your application. It is not possible at all to continue as long as your code is not valid.

To find out about the exception, you can check the Error console (list of the errors) or hover with your mouse over the red line.

// typing error, red underlined:
string myString = "hello world";
Console.WriteLine(mystring);      // compile time exception
 
// must be fixed before you can actually run or successfully compile:
string myString = "hello world";
Console.WriteLine(myString);      // corrected

Open in new window

0
abelCommented:
PS: this behavior is different then for instance PHP, Perl, JavaScript or ASP Classic. These languages are interpreted and as such it is not possible to catch typos in an early stage. Finding errors in your code early is considered a good feature of programming. The opposite, if you'd ship your product or place incorrect ASP/PHP code in a web page and the error only occurs once somebody uses your page or your product, is disastrous.

Being certain that your code is correct is a feature that's automatically available with any language that must be compiled in machine language (VB6, C++, Eiffel) or intermediate language (C#.Net, VB.Net, Java) because the code must be translated and the compiler needs correct code to do so.
0
TheFlyingCorpseAuthor Commented:
ah, yeah.

So its no way to catch these runtime exeptions even if the debugger is able to point it out?
0
abelCommented:
The debugger is not the one that's pointing them out. I can understand the misconception, it seems a bit tricky, but the red line is a result of a partial syntax check and, sometimes, a partial or complete compilation (i.e., some red lines only appear after you do a full compile, others only after you do a compile for the current project, yet others only appear when certain references are available or not etc etc).

It would be too costly (in terms of cpu resources) to do a full compile/debug cycle while you are typing, which is why the concept of syntax errors and compile errors has been invented (this is much more layered then this, but you get the concept).

Once you start debugging (F5, but only with the configuration set to Debug mode) you'll have no red lines (compile time errors) anymore. If the code breaks on an error, you will not see a red line but an informative box with information about the runtime exception. These are the ones the debugger can "point out", but only after certain events have happened (for instance, if the result of user input results in exceptions, i.e., when a number-string is converted to an integer but doesn't only contain numbers but also letters).

-- Abel --
0
TheFlyingCorpseAuthor Commented:
ok, so what you are saying is that what the debugger can point out is what made the exception down to the string if it was in an object on runtime exceptions, but I cannot actually just write a handling for that, I need to prevent it some other way?


Also, how can I check if this has an exception. newapp.Session and newapp.Session.Account both return null when the connection attempt has worked. How can I see if it does not return 0? ;-)
Or have I already done that? (I dont get too clear messages on the popup, while the runtime debug log shows what red values are the ones not correct, ie the UserName!)
try {
   objSession = newapp.session(sTApp, sTKey);
} catch(Exception e) {
   MessageBox.Show("error in objSession: " + e.Message);
}
 
try {
   objAccount = objSession.Account(sUserName, sCmdLine, sPassword, sReserved);
} catch (Exception e) {
   MessageBox.Show("error in objAccount: " + e.Message);
}

Open in new window

0
abelCommented:
Before we continue, let's try to get a few things straight so that we are certain to talk about the same:

  • Are you in Window Forms or ASP.NET?
  • When you see a red line, you can never catch that but you made a typo. Do the variables exist?
  • If you add a try/catch, the debugger will not show the error anymore. But I'm under the impression that you do not need a try/catch at all. Try to run it without it.
  • You can check an object for being null with if(objSession == null). For being 0, you probably have to cast it first. What do you expect inside the objSession, a string, an integer, a string containing an integer?

0
TheFlyingCorpseAuthor Commented:
I am in Windows Forms afaik.

The red line is not in the code, but rather in the locals window, there the value is marked in Red when its wrong.
I also get a yellow line in the codewindow where the balloon window tells me the COMException was unhandled, check the ErrorCode property of the exceptin to determine the HRESULT returned by the COM object.


The error does not show if I do a try/catch, the catch does not execute as I want it to either, it just goes try... done when the string in the locals window is wrong.
0
abelCommented:
The locals window shows a list of most (not all) variables that are currently in scope. It shows a red icon when it cannot find the value of a certain element or of the variable, for instance because evaluation resulted in an error. The Locals window tells you something about the content of variables but tells you little (or nothing) about errors. However, if a variable is set to an error, you can review that contents (as in the screenshot) just like any other variable.

I don't seem to be able to mimic a red line, only a red icon. But usually, any exceptions in the Locals window can be ignored. They definitely cannot be caught, because they run outside of the context of your code. In the rare situation that evaluation of a variable causes your code to fail, you may want to wrap the code that's evaluated in a try/catch block just like any other code.

The balloon window and the yellow line are your real exceptions. That you are talking about HRESULT reveals that you are using COM objects (or ActiveX or COM+ or DCOM or any other variant) which raise their own type of exceptions. It depends on where and how that exception is thrown on what it means. The HRESULT is something that can be useful to match with the documentation of your COM object to find out what's gonig wrong. What COM object are you actually using? Can you share a bit of code so that I can mimic your situation (make it such that it is runnable/compilable).

The two screenshots show how an error looks like in when it's caught and you have a breakpoint and walk through the code with F10. The Locals window shows the content of the Exception object (through the reserved variable $exception).

-- Abel --
ScreenShot428.png
ScreenShot429.png
0
TheFlyingCorpseAuthor Commented:
In the screenshot below you can see what I mean by the red string ;)

To try to make myself clear, its only red here in these strings when the text is wrong, if its correct it is actually black, to the extent I've encountered so far.
If I change a string to be wrong, it shows red, if its not tampered with and is correct to a proper result its black. This is what I want to catch. (The only way to check if its wrong is to do a query to a database other then the locals somehow magically included in exception )

(I use Visial Studio 2008)
localsError.png
0
abelCommented:
The red means in this case that it has just changed. When you walk through your code with F10 you'll see that things turn red when they get a different value. This doesn't always work well (is my experience), which is why I usually favor the Immediate window, or the Watch Windows unless I really need to know all these values. Also, the evaluation can result into side effects (evaluation can call methods before they should actually be called in the cause of operation, but you can't do much about that, it is in the nature of Visual Studio's debugger).

The variable sMessageFilter is a string, it cannot contain, raise or be an error (it may contain the text of an error though).

-- Abel --
0

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
TheFlyingCorpseAuthor Commented:
Thank you very much for your assitance :-)
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
.NET Programming

From novice to tech pro — start learning today.