Global exception handler bypassed in C# async block - c#

What could possibly be wrong with the following block in WP8 SDK? It causes an unhandled exception to be thrown, crashing my debugging session in VS 2012:
try
{
List<StorageFile> files = new List<StorageFile>();
foreach (StorageFile file in (await ApplicationData.Current.LocalFolder.GetFilesAsync()))
if (Path.GetExtension(file.Name).ToLower() == ".item") files.Add(file);
return files;
}
catch (Exception e)
{
var x = e.Message;
return new List<StorageFile>();
}
When I step through, the offending statement is GetFilesAsync(), but I believe at the time I call it, there is no reason why it should fail. In any case, shouldn't my exception handler be called when something goes wrong?

Related

How can I have an exception show in debugging output that doesn't cause a "catch"

This may be a basic question but I have not been able to find an answer from searching. I have code that is causing an exception to be written to the Output -> Debug window in Visual Studio. My try...catch is proceeding to the next line of code anyway. The exception is with a NuGet package.
Does this mean an exception is happening in the NuGet package and is handled by the Nuget package? How can I troubleshoot this further?
private void HandleStorageWriteAvailable(IXDocument doc)
{
using IStorage storage = doc.OpenStorage(StorageName, AccessType_e.Write);
{
Debug.WriteLine("Attempting to write to storage.");
try
{
using (Stream str = storage.TryOpenStream(EntityStreamName, true))
{
if (str is not null)
{
try
{
string test = string.Concat(Enumerable.Repeat("*", 100000));
var xmlSer = new XmlSerializer(typeof(string));
xmlSer.Serialize(str, test);
}
catch (Exception ex)
{
Debug.WriteLine("Something bad happened when trying to write to the SW file.");
Debug.WriteLine(ex);
}
}
else
{
Debug.WriteLine($"Failed to open stream {EntityStreamName} to write to.");
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
The exception happens on the line using (Stream str = storage.TryOpenStream(EntityStreamName, true)) when the exception happens the code proceeds to the next line not the catch.
Is this normal behaviour if that exception is being handled by something else? I've never seen this before.
In general, a method called TrySomething will be designed so that it won't throw an exception, but return some sort of error code instead.
Check for example the Dictionary class : it has an Add method which can throw an ArgumentException if the key already exists, and a TryAdd method which instead just returns false.
Chances are, your IStorage implementation of TryOpenStream also has an OpenStream method, and the Try version is just a try/catch wrapper which outputs the error to the Console in case of error.
How do you know it happens on that line?
However there is a setting that enables breaking handled exception in "Exception Settings" dialog (Ctrl+Alt+E). For each type of exception you can control. Here is a link that explain how it works : https://learn.microsoft.com/en-us/visualstudio/debugger/managing-exceptions-with-the-debugger?view=vs-2022

Eat exception or check null?

I have the following code:
private async Task <string>IsolatedStorageReadTextFile(string uFileName)
{
string sRet = "";
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(uFileName);
if (file != null)
{
using (var inputStream = await file.OpenReadAsync())
using (var classicStream = inputStream.AsStreamForRead())
using (var streamReader = new StreamReader(classicStream))
{
while (streamReader.Peek() >= 0)
{
sRet = streamReader.ReadLine();
}
}
}
return sRet;
}
When the file in question doesn't exist, the IDE throws an error:
Should I
1) let the IDE debug warner ignore this error (say "Don't break on this exception"), and I should just let "if (file != null)" do the job
2) or should I check if the file actually exists
3) use try-catch?
I had to add an important part of code according to the answers:
private async Task <bool> LocalExists(string uFileName)
{
bool b = false;
//https://stackoverflow.com/questions/8626018/how-to-check-if-file-exists-in-a-windows-store-app
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(uFileName);
b = (file != null);
}
catch (Exception ex)
{
b = false;
}
return b;
}
This throws the same exception since in UWP, there seems no other way of checking if a file actually exists than trying to access it:
How to check if file exists in a Windows Store App?
So the question remains.
You should check if the file exists unless it should always be there,e.g. Because it's part of your program.
Nevertheless, you should use try catch around the whole thing because even if the file exists, it could be locked or a different reading error could occur.
Of the three solutions you proposed (ignore the error, check the file exists first, or catch the exception), only catching the exception will work. Ignoring the exception will let the app crash. Checking if the file exists before calling GetFileAsync has a timing issue where the file may be removed after the check but before opening it.
The fourth and best solution is to use StorageFile.TryGetItemAsync to return the file if it exists or null if it doesn't.
StorageFile file = await ApplicationData.Current.LocalFolder.TryGetItemAsync(uFileName) as StorageFile;
if (file != null)
{
//...
}
The linked thread which says there's no way to check was correct for Windows Store apps in 2011. It's out of date for UWP apps in 2017.
You can either check the file exists before, or handle the exception.
When you don't catch the exception, the next line will not be executed so you can't check file for null (not like other programming language like C++).
The option, don't break on this option, only don't pause (activate a breakpoint) the application when exception is thrown only, doesn't change the behaviour of the program.

How can i ignore error to continue project in c# code? [duplicate]

This question already has answers here:
pinvokestackimbalance -- how can I fix this or turn it off?
(5 answers)
Closed 6 years ago.
I am working on a windows form application. when i run the project in one of my class error occurs. (see below image)
But when i press continue button The project runs well. Also, I can not delete this line of code. How can I ignore this error to continue project?
Use try-catch:
try {
// code here
} catch (Exception) {
// do something or nothing if caught
}
Or, if you want to catch a specified exception, do this:
try {
// code here
} catch (/* exception class here */) {
// do something or nothing if caught
}
For instance, if you want to catch NullReferenceException, then do this:
try {
// code here
} catch (NullReferenceException) {
// do something or nothing if caught
}
If you want to use exception data, define exception as a variable, like this:
try {
// code here
} catch (Exception e) {
// do something or nothing if caught
}
In Visual Studio, you can insert a try-catch snippet by typing try and double-hitting Tab key.
There's also try-catch-finally. Example:
try {
// code here
} catch (Exception) {
// do something or nothing if caught
} finally {
// perform some cleanup here
}
In Visual Studio, you can type tryf and double-hit Tab key to insert a try-catch-finally snippet.
You can also just perform some cleanup using try-finally without getting any error:
try {
// code here
} finally {
// perform some cleanup here
}
More info on MSDN about try-catch, try-finally and try-catch-finally.
But still, if an error occurs, that mean something is wrong. Google some information about it.
You can try using trycatch :
try{
//your code
}
catch(Exception ex)
{
//Log the exception 'ex'
}
You are looking for TryCatch handling:
// some code
try
{
// "try" some code here
// You may put the line that may cause an error here
} catch(Exception ex)
{
// This part will get executed if above did not work (error - threw an exception)
// You may just keep it empty -> error will be ignored
// or log `ex` information
// or do something anything else
}
// control will continue - no crash
// some other code
For more information, Read C# - Exception Handling.

C# User Defined Exception handling for Erroe from Dll get Exception was unhandled by user code

i am working with dynamic c# application that links all the classes into the main application from the Dll files that i create separately, in these files when i connect my dll file dynamically the error handlers want throw the errors by the connection as it used to be here is what i try to do
i have a dll file with this coding and class on it
class clsGlobles
{
public object dlststus = false; // dtabase file status
public clsGlobles()
{
try
{
if (dlststus == true)
{
}
else
{
throw new Exception("Some important files are missing - Please re-install the application"); //throw this as a error and stop running the program
}
}
catch (Exception ex)
{
throw ex; //throw exception to the upper throw catch exception where i like to hand it
//Evan i use throw; instead of throw ex; i get the same result
}
}
and then i link this dll file by using dynamic method it works well but when i try to pass the user define error then i get error as unhanded exception and being show the class inside the dll file, i don't wants to handle any exception in my classes in dll file just need to pass them to the next step and handle them in the program where i use them.
here is the code where i use it
private void frmMain_Load(object sender, EventArgs e)
{
string tf = "";
tf = Application.StartupPath + "\\clsGlobles.dll";
try
{
Assembly asm = Assembly.LoadFrom(tf);
AppDomain.CurrentDomain.Load(asm.GetName());
Type type = asm.GetTypes().First(t => t.Name == "clsGlobles");
glbls = Activator.CreateInstance(type);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString()); // the error i throw in inside the dll class should come here and i could handle it from here
}
}
and when i close the above error box and continue run it also shows something like this
i think i get the answer here, when i link my dll into the application by reference and then using it as a object inside of my application by using directive it works fine and lets me to use throw exception to the application's throw catch statement, but when it added into the application by dynamically it expect me to handle my exceptions inside the dll and solve what ever the problems, it wont allow me to throw exceptions by using throw new exception("err") to the application
Evan a there is no err handling for that throw new exception is okay, but it wont allow the throw in catch block

Handling an exception on items in a for-each loop

I couldn't think of a good way to test it myself so asking this question:
Lets say I have a list of transactions that I have sending them one by one to a web service and the result of webservice call may be Success, Failed or something weird may have happened and it just crashes.
So the overall code I have is like this:
for each (transaction)
{
try
{
string result = webservice.Call(transaction);
if result == "Faild"
{
// log some errors.
}
}
catch (Exception ex)
{
// Log some errors, stack trace, etc...
}
}
So my question is: if it falls into an exception for one of the transaction calls, then does the whole thing stop? OR it will get out of the exception block and will move on to next item in the for-each?
A catch is a catch and will do what a catch is supposed to do.
The loop will not break unless you rethrow the exception.
If you want to complete the entire loop before telling the user that something went wrong you can do
something like this:
List<Exception> exceptions = new List<Exception>();
foreach (var transaction in transactions)
{
try
{
string result = webservice.Call(transaction);
if result == "Faild"
{
// log some errors.
}
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
if (exceptions.Any())
throw new AggregateException(exceptions);
It WILL continue looping until you have no more transactions to loop through. That's what is so useful about try catch.
Since the try/catch is inside the loop, it will run for each transaction call.
If you had put the loop inside the try, then it would blow up at the first exception.
Check out the information here on using try { ... } catch() { ... } finally { ... }, where you can have code that executes after the exception is handled.

Categories