Find catch corresponding to a throw in Visual Studio - c#

When using gotos in c# Visual Studio helps quite well with figuring out the controll flow. Shift-F12 on the label shows me from where the part is reached, and F12 on the goto statment goes to the label.
But I usually use no gotos in my code. In allmost all cases stuctured programming or exceptions seem to be better.
However, when using exceptions the controll flow can be just as confusing as using gotos. Has visual studio equivalent functions for exceptions? e.g. find all throws that one catch could catch, and find the corresponding catch for a throw?

Open your project -> Debug -> Windows -> Exceptions -> Check every kind of exception you are interested about

c# don't have a goto like Visual Basic 6:
You only have to do a:
Try
{
....
}
Catch(Exception ex)
{
String err = ex.Message;
}
You can see this as your reference

Related

Selecting Catch Block (in visual studio) with Regular Expression Search

I want to select all catch blocks (in my C# code in visual studio) using regular express search but unable to create a regular expression that selects all catch blocks (including empty blocks and blocks with different exception handling)
I have tried following regular expressions but failed
.*catch.*(\r?\n)*.*(})
.*catch.*(\r?\n)*\s*.*(\r?\n)*.*(\r?\n)*
I have found the solution, regular expression catch(.|\n)*?} will select all catch blocks

c# cannot write file in specific computer (Solved but don't know reason)

I have three computers for testing.
When I write files by my program in XP(PC, and it's my platform of developing) and Win7(PC), both are work.
But in one win7 computer(laptop), it cannot write and no exception come out.
Since Win 7(PC) can run my program perfectly, I think it's not the problem of win 7.
I find that when I use my c# program, it can read but cannot write file.
I try to set the path to c:/Users/Local/AppData and still doesn't work...
The permission to read and write can be accessed, and I can write file manually so maybe it's not because of memory leaking.
And I have tried to open my program in administrator mode.
I don't know any other reason why my program cannot write file in that computer.
I also tried to create directory as:
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
if (!Directory.Exists(Path.Combine(appDataPath, "test")))
{
try
{
Directory.CreateDirectory(Path.Combine(appDataPath, "test"));
}
catch (Exception ex)
{
MessageBox.Show("" + ex.ToString());
}
}
The code can work in PC(XP and Win7), but still doesn't work in laptop(Win7)...
I also use MessgeBox.Show below the CreateDirectory method, and it can pop out the test message!( that is, the code of CreateDirectory is ran but when I look the parent directory, there isn't exist directory I want to create......( but in PC, the directory is created), I have seen someone have same problem, but the solution doesn't help me......
The code of writing file is:
try
{
StreamWriter file = new StreamWriter(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\logfile.txt");
file.Write("test");
file.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Why the strange laptop cannot write files by my program?
Edit:
My program have some operation in the textbox to record data to be saved,
the operation is: When user click at the textbox, the osk.exe( small keyboard) will show up. In my laptop, the osk.exe will show error when I want to run it......
The code to osk.exe is:
System.Diagnostics.Process.Start("" + System.Environment.SystemDirectory + "/osk.exe");
While I remove that code, the code to write file simply worked!
Maybe the reason is I check empty textbox first, then user click 'Save' button to write file. Since error occur when the code try to run osk.exe, the textbox may return null or something, then my code of write file won't be operated.
I know it's hardly possible but I had similar issue lately:
If you don't get an exception it can be caused by version mismatch of .NET Framework on your machines. This means that if some method got new overload that you're using and it's not implemented in previous version of .NET then it throws exception in the .NET internally while JIT compiler will try to compile the IL.
Had the same issue with the method PropertyInfo.GetValue(object) -> in previous version there was no such method but PropertyInfo.GetValue(object, object[])
Try to set (in the project properties) target framework that matches the framework you have installed on not working machine. If it compiles then you have to look for another solution.

Application closing unexpectedly c#.net

I have inherited a large system and I am having a strange issue where I click on a button and the entire application crashes, this is when I include the latest dll in an update. I get no exceptions or Not responding etc and the application just closes completely. I am unsure why this is.
All I need to know is what could be the possible causes of this, is it an un-handled exception and would I need to locate this? The strange thing also is that it is working locally, only when I publish and run on the server.
Any ideas to get me started would be appreciated.
Thanks
When connecting to a server you should always include some sort of exception handling in your code. E.g try catch which allows you to print the exception message in a message box to clearly know whats going on.
try
{
//here you will have all the code that takes care of the database connection
}
catch(Exception e)
{
// log error here.. E.g MessageBox.Show(e);
}
This is the standards you should follow when it comes to server connections. This will also prevent your system from crashing.

C# command line project - Error when run via .exe

I have a C# project that compiles normally. When I run the project via Visual Studio's IDE it runs fine and ends cleanly. However when I navigate to the project directory and attempt to run the program by double clicking the "exe" file or referencing it via the run window it errors out.
I have narrowed the problem down to
Console.WriteLine("output ->" + any_variable);
For some reason if I print any variable using the console.writeline the application will error if ran as described earlier.
If I take this line out, the executable created by the Visual Studio will run just fine if i double click on it. I'm really confused by this. My goal here is to create this command line project as a scheduled task.
I'd assume the error not having anything to do with WriteLine or even a Console. While a common a difference between running from IDE and running from double-clicking might be the rights (i.e., you may start the IDE as admin, or the location that you are writing/reading from/to is different and has different ACLs attached to it), thiis doesn't seem to be the case here.
To catch your actual error, compile into debug mode. Start your application (possibly with a message box of some kind). Start the IDE and select Debug and Attach to process (you have all the time if you pause your app with a message box). Select your process. Run until you receive the error. You should now receive the error in the IDE, even though the app is run from double clicking the EXE. You can see the stack and debug as you would normally do.
My guess? The variable you're printing does something that raises the error.
Altenatively: a simple try/catch around the offending statement plus a messagebox with the Exception.Message should give you some more intel too.
I'm sorry, I was wrong... so EDIT
Place your code into try{} catch{} construct:
try
{
//your code goes here
}
catch (Exception ex)
{
Console.WriteLine("An error occured: {0}", ex.Message);
if (ex.InnerException != null)
Console.WriteLine("Inner Exception: {0}", ex.InnerException.Message);
Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
}
This is neccessary to find out were is your problem, at which line of code etc.
I don't know if this applies to your case or not, but I had a very similar issue that I posted here the other day: Weird error message when running my application

C# WriteDirectory Issue

I have an application that writes to a folder on the C:\ drive. The program works fine on my computer, but on another laptop when running the .exe (The other laptop has no visual studio etc.), i get a filenotfoundexception and i cannot pinpoint the line of code where this happens from the error report.
Here is the code for creating the directory (assuming this is the issue)
try
{
WriteDirectory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\SMS Notifier\");
if (!WriteDirectory.Exists)
WriteDirectory.Create();
}
catch (Exception e)
{
throw e;
}
Any ideas what the problem could be?
Should i check for write permission ?!
Help greatly appreciated!
If you deploy the .pdb files along with your .dlls, you will get line numbers in the exception messages!
Your try..catch block isn't doing anything useful, all it is doing is swallowing the stack trace so you cannot see what is going on! I'd suggest removing the try..catch block entirely.
throw e; causes the stack trace to be lost, use throw; to preserve it.
Also you should use System.IO.Path.Combine() to append the directory root and the sub-directory name, that way you don't have to worry about doing the \'s yourself and possibly making a mistake.
My guess is that this isn't the real issue; neither DirectoryInfo.Create nor
Directory.CreateDirectory throw a FileNotFoundException.
Best bet is to build the app for debug, then copy the file along with all it's .pdb files; hopefully this'll give you the methods and line numbers in your error message.
You might also consider adding a handler for any unhandled exception; the AppDomain.UnhandledException can be handled so that you can add your own event handler for any unhandled exception running anywhere in the app;
Add something like this to your Main function;
System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
And then write your own handler for the error;
static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
}
Does this path exists on the Laptop?
Environment.SpecialFolder.ApplicationData
Do a debug.writeline on this line like a messagebox.show and see what the path is?
Also if the path exists it may be a permissions issue..most likely
First thing I might do (for debugging purposes) is to insert a
MessageBox.Show(WriteDirectory.FullName);
before you try and create the directory just to see if that "Special" path is what you think it is!
Using throw; rather than throw e; will preserve the original stack trace in the exception.
Putting a Console.WriteLine(e.ToString()); (or a MessageBox equivalent) in the catch block will output the stack trace then and there (you will want a debug build for most information).
If all else fails, the old standard of trace statements Console.WriteLine("about to do x"); will help -- with the app launched from a command line.
Is .Net framework installed on the laptop ?
other possibility : the plateform doesn't support this directory. Check compatible plateforms on msdn

Categories