How to check error message in C#? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is that a way to check error message shown after negative values? I can check if the correct exception was thrown, but what if my method won't throw an exception with negative numbers, just WriteLine to Error output stream.
public List<int> MyMethod()
{
...
try
{
//add elements to list
}
catch(Exception e)
{
Error.WriteLine("Element cannot be negative, but other elements are ok");
}
...
}
[TestMethod]
public void TestWithNegatives()
{
try
{
List<int> list = MyMethod();
//there is a negative int in list, so there'll be an error message
}
catch (Exception e)
{
//Can I check here the error message, if there isn't exception thrown in mymethod?
}
}

Since you already handled the exception and it is not rethrown, you cannot handle it again in your test.
But since you know that a message is written to Console.Error, you can check this by redirecting Console.Error to a custom StringWriter and check what was written to it like that:
public void TestWithNegatives()
{
using (StringWriter sw = new StringWriter())
{
Console.SetError(sw);
List<int> list = MyMethod();
// Check output in "Error":
Assert.IsFalse(string.IsNullOrEmpty(sw.ToString()));
}
}

Related

Continue program after exception is caught? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
i know this question has been asked similarly quite often, but I can't seeem to find an answer that I'm satisfied with. I want do learn this "right" from the start.
string [] list = {"foo", "bar", "foo"};
for(int i = 0; i<list.Length;i++)
{
try
{
//begin sql transaction
if(!list[i].Equals("foo"))
throw new Exception("foo exception");
else
{
//save stuff into DB
Console.WriteLine(list[i]);
//commit transaction here
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
//rollback transaction here
}
Console.WriteLine("Next record");
}
I've tested the code in the following fiddle https://dotnetfiddle.net/0nftFD and now my questions:
If i were to handle files in a for loop analog to the above example and if one of them had an IO exception for example, i would log it, email to admin, etc. and then continue with the next file.
As far as i can see it would work like this, would this be good/bad practise? I'd like to learn this properly right away :)
EDIT: Because i failed to mention this before, I would also get specific exceptions.
Ressources i failed to see before:
similar question: https://forums.asp.net/t/1943641.aspx?How+do+I+continue+after+an+exception+is+caught+
.net site: https://learn.microsoft.com/de-de/dotnet/csharp/programming-guide/exceptions/using-exceptions
Depending on the requirements you might be able to separate the data processing and error handling:
Iterate through the files
In case of exception capture into enough information into a List, Dictionary to be able process later
After looping through all the object loop through the errors
For example:
string[] list = {"foo", "bar", "foo"};
var errors = new Dictionary<string, ExceptionDispatchInfo>();
for(int i = 0; i < list.Length; i++)
{
try
{
if(!list[i].Equals("foo"))
throw new Exception("foo exception");
else
Console.WriteLine(list[i]);
}
catch(Exception ex)
{
var edi = ExceptionDispatchInfo.Capture(ex);
errors.Add($"{list[i]}_{i}", edi);
}
Console.WriteLine("Next record");
}
foreach(var error in errors)
{
//Process error and throw the original exception if needed
//error.Value.Throw();
}
Your example is how to handle it, though you may wish to catch only specific exceptions and not all. In some cases you may want to exit the processing due to speicific exceptions - for instance - if your database is not reachable then no need to keep going through all the files only to find it fails on each iteration.
In that example you could nest the loop in a try catch also such that it may catch exception types that are thrown which you specifically wish to be terminal to the loop processing. An example of it being nested is shown below.
try
{
for(int i=0; i < 100; i++)
{
try
{
//do something
}
catch(IOException ex)
{
}
}
}
catch(SecurityException sex)
{
}
Incidentally - you might also consider that you can batch the database (depending how many files you might be processing) and make your changes in one go. That's a performance trade-off you might wish to consider.

C# how to capture stored procedure exceptions? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code:
using (var reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var recibir = reader.VisibleFieldCount;
var rear = reader;
response.Add(new Cuota
{
opcion = (int)reader["PC_NUMERO_OPCION"],
cuota = (int)reader["PC_NUMERO_CUOTAS"]
});
}
}
I am trying to get the exceptions of SQL Server, what are the corresponding methods?
In general, you can catch a SQL Exception using the SQLException class. It works like this:
try
{
// your code that calls the database here
}
catch (SqlException e)
{
// your code that handles the Sql Exception
}
I typically add a double catch, just in case there is some other error in my code tht isn't SQL related:
try
{
// your code that calls the database here
}
catch (SqlException e)
{
// your code that handles the Sql Exception
}
catch (Exception ex)
{
// your code that handles normal exceptions
}

Catch specific exception instead of "Exception ex" [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm inserting data to a database and I guess some kind of exceptions might occur here, possible more than one?
ussually I used to write something like this:
try
{
//Execution code
}
catch(Exception ex)
{
// log error and throw it
}
And I think it's better to catch some specific exception instead of (Exception ex) something like this:
try
{
// my possibly bad code which inserts data to db
var someEntity = CreateEntityFromDTO(someDTO);
_context.SomeThing.Add(someEntity);
await _context.SaveChangesAsync(cancellationToken);
}
catch(MySpecificException mse)
{
// log error and throw it
}
What might be best practice when it's about catching exception while inserting data to db ?
Thanks
Cheers
You could make your SpecificExceptions inherit from another higher level DatabaseException and handle all Database Exceptions in one catch clause like
public class DatabaseException : Exception {}
public class MySpecificException : DatabaseException {}
public class YetAnotherDBSpecificException : DatabaseException {}
try
{
// insert data.
}
catch(DatabaseException dbEx)
{
// A database exception occured.
Console.Log(dbEx.Message);
}
catch(Exception other)
{
// Non db exception occured.
Console.Log(other.Message);
}

Writing a function to handle exceptions in C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Is it reasonable to think I can write a void function to take in an Exception and output the stuff that a catch block normally would? Here's an example of my exception catcher (which I would make individual ones for common exceptions I handle):
private void exCatch(Exception ex)
{
MessageBox.Show("ERROR - " + blah blah blah + ex.ToString(), blah blah);
}
Here it is in practice:
try
{
stuff
}
catch (Exception e)
{
exCatch(e);
}
Is this an efficient way to handle exceptions? If this is reasonable, do people do this? It seems like it could speed up your coding not having to copy paste all your exception junk over and over. Thanks for any help!
There is no problem with that at all. In fact, adding functions to reduce code repetition is definitely advisable. Then if you want to change say the MessageBox buttons you change it once and you're done everywhere.
One note is that you should consider only catching certain types of exceptions that you're expecting. If you're catching an exception it should be because you know where it came from and exactly what to do with it. Or else you might be catching something that should be handled at a higher level and your app can get into an invalid state. Here's an example.
ArgumentNullException
FormatException
OverflowException
Are the exceptions that Int32.Parse(string) throws. Lets say you know you wont be passing in Null this is how MSDN shows you should handle the function:
using System;
public class Example
{
public static void Main()
{
string[] values = { "+13230", "-0", "1,390,146", "$190,235,421,127",
"0xFA1B", "163042", "-10", "007", "2147483647",
"2147483648", "16e07", "134985.0", "-12034",
"-2147483648", "-2147483649" };
foreach (string value in values)
{
try {
int number = Int32.Parse(value);
Console.WriteLine("{0} --> {1}", value, number);
}
catch (FormatException) {
Console.WriteLine("{0}: Bad Format", value);
}
catch (OverflowException) {
Console.WriteLine("{0}: Overflow", value);
}
}
}
}
https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx
Always look up the exceptions that a method can throw and always document those that you are catching and throwing in your methods.

Handling two WebException's properly [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
I am trying to handle two different WebException's properly.
Basically they are handled after calling WebClient.DownloadFile(string address, string fileName)
AFAIK, so far there are two I have to handle, both WebException's:
The remote name could not be resolved (i.e. No network connectivity to access server to download file)
(404) File not nound (i.e. the file doesn't exist on the server)
There may be more but this is what I've found most important so far.
So how should I handle this properly, as they are both WebException's but I want to handle each case above differently.
This is what I have so far:
try
{
using (var client = new WebClient())
{
client.DownloadFile("...");
}
}
catch(InvalidOperationException ioEx)
{
if (ioEx is WebException)
{
if (ioEx.Message.Contains("404")
{
//handle 404
}
if (ioEx.Message.Contains("remote name could not")
{
//handle file doesn't exist
}
}
}
As you can see I am checking the message to see what type of WebException it is. I would assume there is a better or a more precise way to do this?
Based on this MSDN article, you could do something along the following lines:
try
{
// try to download file here
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
// handle the 404 here
}
}
else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
{
// handle name resolution failure
}
}
I'm not certain that WebExceptionStatus.NameResolutionFailure is the error you are seeing, but you can examine the exception that is thrown and determine what the WebExceptionStatus for that error is.

Categories

Resources