Why is try catch sometimes ignored? - c#

One example is this code:
try
{
string domain = o.SelectToken("response[" + i + "].domain").ToString();
...
}
catch(Exception)
{
continue;
}
Instead of just going on in the loop("continue"), vs halts and points at string domain = o.SelectToken("response[" + i + "].domain").ToString(); for an System.IndexOutOfRangeException.
Why is that?

You probably have 'break on all exceptions' selected in the Debug>Windows>Exception settings:
https://learn.microsoft.com/en-us/visualstudio/debugger/managing-exceptions-with-the-debugger?view=vs-2019
Unselecting this will let VS proceed.

You can do it by using two ways.
As suggested in MSDN, is to set it up in your Visual Studio (I believe it's 2019)
Debug > Windows > Exception Settings: Search for index and untick.
Please add exception to handle exception in your code..
catch(IndexOutOfRangeException e)
{
// handle it like logging it in file and continue
continue;
}
catch(Exception)
{
continue;
}

Related

Exception not being caught in c#

I have the following code and my code does not catch the exception.
In my code I am trying to read all the files for which the access is granted.
var pathsToSearch = new Queue<string>();
var foundFiles = new List<string>();
pathsToSearch.Enqueue(startFolder);
while (pathsToSearch.Count > 0) {
var dir = pathsToSearch.Dequeue();
try {
var files = Directory.GetFiles(dir);
foreach (var file in Directory.GetFiles(dir)) {
foundFiles.Add(file);
}
foreach (var subDir in Directory.GetDirectories(dir)) {
pathsToSearch.Enqueue(subDir);
}
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e);
}
}
Why does the try catch not work properly or is there some mistake in my code ?
It sounds like you're running your program from Visual Studio, which catches First Chance Exceptions by default. You can turn off this option in Visual Studio. I believe this is under Debug > Exceptions, but you may also be able to disable this from the popup dialog that displays the exception.
Here's a Microsoft article that might be helpful: Understanding Exceptions while debugging with Visual Studio

What is the common way to throw exception if my exe file that i need to start does not exist on the machine

in my application i am start capinfos.exe that is part of Wireshark.
in the constructor i am check if Wireshark install on the machine:
private string _filePath = "";
public Capinfos(string capturePath)
{
if (Directory.Exists(#"C:\Program Files (x86)\Wireshark"))
{
_capInfos = #"C:\Program Files (x86)\Wireshark\capinfos.exe";
}
else if (Directory.Exists(#"C:\Program Files\Wireshark"))
{
_capInfos = #"C:\Program Files\Wireshark\capinfos.exe";
}
_filePath = capturePath;
}
what is the best way to do it and throw an exception if the file does not exist on the machine: please install Wireshark
private string _filePath = "";
public Capinfos(string capturePath) throws FileNotFoundException
{
if (Directory.Exists(#"C:\Program Files (x86)\Wireshark"))
{
_capInfos = #"C:\Program Files (x86)\Wireshark\capinfos.exe";
}
else if (Directory.Exists(#"C:\Program Files\Wireshark"))
{
_capInfos = #"C:\Program Files\Wireshark\capinfos.exe";
} else
{
throw new FileNotFoundException(#"Wireshark installation not found");
}
_filePath = capturePath;
}
You can then catch the exception by using this code:
try
{
Capinfos("path");
}
catch (FileNotFoundException ex)
{
Messagebox.Show("Please install wireshark.");
}
I don't have C# installed, this was written by hand. Hope it's fine!
Here's an excellent resource to learn on exceptions: http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx
Something like:
throw new FileNotFoundException("Could not find " + _capInfos, _capInfos);
Not sure if this is what you want, but try to use a try-catch block. You could attempt to start the .exe in the try block and if it fails, throw a FileNotFoundException and create a popup box in the catch block that will alert the user of what they need to do.

Windows Service doesn't read settings.setting?

I have a Setting.setting have a setting option : isSent - type int - value : 0
And my code :
if (Settings.Default.isSent =! 0)
{
var info = _text.ReadFile(Settings.Default.FilePath);
//Do something
} else
{
//Do something
}
I install my Windows Service, start and attach it to Visual to debug, and it always run to
var info = _text.ReadFile(Settings.Default.FilePath);
But not run to
} else
{
//Do something
}
like I expect :(
Anyone can explain it and know how to solve this for me ? Appreciate any answer :)
I just noticed "if (Settings.Default.isSent =! 0)". Should it be "if (Settings.Default.isSent != 0)". Otherwise visual studio will always report error.
by the way, have you tried to attach your source code to the Service and see the value of "Settings.Default.isSent" at runtime?

"Class is not licensed for use" error

In a Win32 C# App, when I run my application and hit some button I get this error ""Class is not licensed for use" and jumps to this code in my VS....
if (oUCMRWPTemplate.ResultLayoutExistsInd)
{
try
{
if (oTextSvc_UnmarshallText == null)
{
oTextSvc_UnmarshallText = new SelectTemplate.TextSvc();
}
int replyHandle = lReply.Handle.ToInt32();
sText = new StringBuilder(oTextSvc_UnmarshallText.BuildTextFromSRV(ref replyHandle, moUCMRWPTemplateLoadQual.PageWidth));
}
catch { }
}
Debugger stops at the line that says sText = new StringBuilder....
I was wondering from this point what should I look at to find what is the issue?
I suspect the problem is your moUCMRWPTemplateLoadQual instance. This is likely a third party control which is not properly licensed.
The reason the debugger stops on that line is that is where you retrieve a property (PageWidth) which is obviously checking licensing.

Show line number in exception handling

How would one display what line number caused the error and is this even possible with the way that .NET compiles its .exes?
If not is there an automated way for Exception.Message to display the sub that crapped out?
try
{
int x = textbox1.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Use ex.ToString() to get the full stack trace.
You must compile with debugging symbols (.pdb files), even in release mode, to get the line numbers (this is an option in the project build properties).
To see the stacktrace for a given Exception, use e.StackTrace
If you need more detailed information, you can use the System.Diagnostics.StackTrace class (here is some code for you to try):
try
{
throw new Exception();
}
catch (Exception ex)
{
//Get a StackTrace object for the exception
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
}
This will only work if there is a pdb file available for the assembly. See the project properties - build tab - Advanced - Debug Info selection to make sure there is a pdb file.
If you use 'StackTrace' and include the .pdb files in the working directory, the stack trace should contain line numbers.
string lineNumber=e.StackTrace.Substring(e.StackTrace.Length - 7, 7);
this way you can Get Line number from Exception
public int GetLineNumber(Exception ex)
{
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
int ln=0;
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
string lnum = System.Text.RegularExpressions.Regex.Match(lineNumberText, #"\d+").Value;
int.TryParse(lnum,out ln);
}
return ln;
}
Line numbers will be included in the stack trace if the library which generated the exception is compiled with debug symbols. This can be a separate file (*.pdb) or embedded in the library.
For .NET Core, .NET 5 and later, to have full exception line numbers in release builds, configure the project as follows:
<PropertyGroup>
<DebugSymbols>true</DebugSymbols>
<DebugType>embedded</DebugType>
<!-- Only enable the following if the line numbers mismatch -->
<!--<Optimize>false</Optimize>-->
<!--
Additional properties which may impact how printed line numbers match the source code line numbers are listed here:
https://learn.microsoft.com/en-us/dotnet/core/run-time-config/compilation
-->
</PropertyGroup>
The above configuration will include debug symbols directly with the built files, which can be published as nugets.
An alternative to the above is to restore debug packages together with the main nuget packages, which is currently not yet supported: https://github.com/NuGet/Home/issues/9667
Now get the exception line numbers:
try
{
throw new Exception();
}
catch (Exception ex)
{
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(0);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
}
Is it possible to simply get the top frame from the StackTrace exposed by ex?
try
{
throw new Exception();
}
catch (Exception ex)
{
// Get the top stack frame
var frame = ex.StackTrace().GetFrame(0);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
}

Categories

Resources