Question:
C# help (try-catch exceptions)?
Mama Luigi
2013-03-19 11:46:42 UTC
So let's say that I have a text file that has hundreds of words. I want to use a try-catch exception method that will only write out all of the five-letter words in the .txt file. This is being coded in Visual Studio 2012.
I understand the basic syntax of a try-catch and what it does (thanks to this: http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.80).aspx), but I'm not entirely sure how to approach the problem. It seems to me that all this method would do is just print out "I caught this exception!", instead of actually printing the words.
Help please?
Three answers:
Almighty Wizard
2013-03-19 11:53:36 UTC
You may understand the syntax, but I don't believe you truly understand the use of exceptions. Exceptions should only be used for exceptional situations, such as trying to access an array element with an index that doesn't exist or perform an operation on an object that is null. You should not use exceptions for logical flow.



Why don't you just use a loop and check the length of each word?



// psuedocode

string[] words = file.readAllFile().split(" "); // read contents and split on spaces

for each word in words



if word.length == 5 then print word

else do nothing



end for
anonymous
2016-12-01 15:22:28 UTC
The code interior the seize block is what executes if an exception is thrown. working example, if the consumer has entered "steve" interior the text textile field, int.Parse() will throw an exception because of the fact this might't be parsed as an int. if so, a would not have a fee, so which you would be able to no longer verify its fee in an if fact.
Lord Daniel Vogel
2013-03-21 09:31:39 UTC
What almightywizardoftheworld is correct, but if you really wanted to solve this using try catch, I would suggest (pseudocode):



for each word in file {

try {

word.length == 5 then throw new Exception(word)

} catch E {

Print E

}

}



Even tho, it doesn't make any sense to use this approach.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...