Keep getting Exceptions on correct Catches [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 9 years ago.
Improve this question
I am in need of some help with a small problem.
I've got 2 strings that needs to be put in order a parameter box in Task Scheduler. But I want to catch the System.FormatException that occurs when somebody accidentely switches them.
But whatever happends, I keep getting the same error. I also added a catch in case either one or both of them hasn't been put at all. Because if that happends, a System.IndexOutOfRangeException error will occur. Basicly my code does the following:
try
{
//Processing the inputted parameters
}
catch(System.FormatException e)
{
Console.WriteLine(e.Message);
}
catch(System.IndexOutOfRange.FormatException e)
{
Console.WriteLine(e.Message);
}
I tested these two catches separately. But either way I get the error.
I've seen some examples, but those were made specifically for some methods.
If anyone can help me out with this issue, I'd appreciate it! :)
Edit
Current catch:
catch(Exception e)
{
Console.WriteLine(e.Message);
streamwriter.Close();
filestream.Close();
}
Edit
The error:
Unhandled exception: System.FormatException: the format of the input string is incorrect.
at System.Number.StringToNumber < NumberBuffer String str, NumberStyles options, NumberFormatInfo info, Boolean & number, parseDecimal >
at System. Number. ParseInt32 < String s, NumberStyles style, NumberFormatInfo info >
at System. Convert. ToInt32 < String value > at LastWriteAccess_Checker. Program. Main < String [] args >
This all refers to the input parameters in the code. One being int that gets converted to string.

This answered the original question which has now been edited, so it might not be an appropriate answer in light of the edits.
To catch both exceptions and react to them you can write this.
catch (Exception ex)
{
if (ex is FormatException || ex is IndexOutOfRangeException )
{
Console.WriteLine(ex.Message);
}
else
{
throw;
}
}
finally
{
streamwriter.Close();
filestream.Close();
}
You can put a breakpoint at the catch to see what the actual exception being caught is.
You should close resources in the finally block, not the catch block

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.

Try Catch to Handle Exception [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 4 years ago.
Improve this question
I am trying to update some documents in DocumentDb / CosmosDb, and if that fails, need to do something else, and then if that fails to log it out...
try {
do a thing w/ database
}
catch (DocumentClientException dce1) {
try {
do another, alternative thing w/ database
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
I'm not sure about this, it seems clunky.. what do you guys think?
For additional bonus points, I need to do this quite frequently.. so something that I can farm off somewhere would be even better ;)
Personally I'd avoid intermixing exception flow with a functional logic flow. It can get brittle. Instead, convert the exception into a logical flag and use it in ordinary logic constructs.
So step 1 is catch the exception and set a variable or return value based on it, and wrap this in an independent method to mask the messiness from everyone else:
bool TryDoSomethingWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
bool TryDoSomethingElseWithDataBase()
{
try
{
//Do thing that could fail
return true;
}
catch(SpecificException ex)
{
return false;
}
}
Step 2 is to write the logic as usual:
if (!TryDoSomethingWithDatabase())
{
if (!TryDoSomethingElseWithDatabase())
{
LogFatalError();
}
}
Or
var ok = TryDoSomethingWithDatabase();
if (ok) return;
ok = TryDoSomethingElseWithDatabase();
if (ok) return;
LogFatalError();
Why would your thing with the Database fail? You would be better coding for the conditionals you are aware of and expecting and do different things if you want to go into a different logic for processing the result.
Try catch will catch anything and everything, so if your connection to the db fails etc or if you are trying to read or insert malformed data etc.
Try catch does have various exceptions that you can investigate further and catch the specific exception you are interested in.. e.g.
try
//try something
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
//Do something specific;
return;
}
throw;
}
This is ok but if you say you'll have this over and over it's better to extract that logic and reuse it.
One way of doing this is to have a method that accept the first and section actions as parameters, for example:
public void TryThis(Action doFirst, Action doSecond)
{
try {
doFirst();
}
catch (DocumentClientException dce1) {
try {
doSecond();
}
catch (DocumentClientException dce2) {
log to app insights.
}
}
}
And then use it like so:
public void DoSomethig1()
{
...
}
public void DoSomething2()
{
...
}
TryThis(DoSomething1, DoSomething2)

Make the error shorter

I made a program in c#(I don't put here the code because there are lot of classes),and I made Exceptions to throw the mistakes,and when a mistake occurs this is what appears in the console:
System.Exception: Student whit id:1 already exists! at
StudentManagment.Service.AbstractService`4.Add(E entity) in
C:\Users\Robbi\source\repos\StudentManagment\StudentManagment\Service\AbstractService.cs:line
34 at StudentManagment.Domain.Program.Main(String[] args) in
C:\Users\Robbi\source\repos\StudentManagment\StudentManagment\Program.cs:line
23
And my question is, How can I make that in the console to appear just
Student whit id:1 already exists!
Catch the exception into a variable and output the exception.Message only. You are seeing a stack trace - ie all the methods that are in execution at the point of error. StackTraces are useful for debugging purposes, but not so great for displaying information to a user.
i.e
try
{
//do error here
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
This is a very beginner issue
While you show no code, heres some semi fake code to answer the question
try
{
do_it();
}
catch (Exception myEx) // you can do different things with different exception types
{
Console.WriteLine("Error: "+myEx.Message);
}
You have to use
ex.Message
where ex is your exceptption, something like
try
{
...
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
Of course, edit this minimal snippet code to satisfy your needs

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