Solved

Error catching in C#

Posted on 2009-07-11
14
496 Views
Last Modified: 2013-12-17
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

0
Comment
Question by:TheFlyingCorpse
  • 8
  • 6
14 Comments
 
LVL 39

Expert Comment

by:abel
ID: 24829666
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
 
LVL 39

Expert Comment

by:abel
ID: 24829677
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
 
LVL 2

Author Comment

by:TheFlyingCorpse
ID: 24830890
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
 
LVL 39

Expert Comment

by:abel
ID: 24831403
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
 
LVL 39

Expert Comment

by:abel
ID: 24831433
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
 
LVL 2

Author Comment

by:TheFlyingCorpse
ID: 24832792
ah, yeah.

So its no way to catch these runtime exeptions even if the debugger is able to point it out?
0
 
LVL 39

Expert Comment

by:abel
ID: 24834168
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 2

Author Comment

by:TheFlyingCorpse
ID: 24834323
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
 
LVL 39

Expert Comment

by:abel
ID: 24834606
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
 
LVL 2

Author Comment

by:TheFlyingCorpse
ID: 24834809
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
 
LVL 39

Expert Comment

by:abel
ID: 24834960
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
 
LVL 2

Author Comment

by:TheFlyingCorpse
ID: 24835008
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
 
LVL 39

Accepted Solution

by:
abel earned 500 total points
ID: 24857927
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
 
LVL 2

Author Closing Comment

by:TheFlyingCorpse
ID: 31602390
Thank you very much for your assitance :-)
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now