Try/Catch - "Code style" question - c#

In general I want to make a code that makes a call an Execute function of a class which may throw an exception. My question is should I setup the class and should I extract the values from it within the try/catch or out side?
Option A:
neededValue V;
try
{
MyClass C = new MyClass();
C.SomeParam = XXX;
C.Execute();
V = C.SomeParam2;
}
catch
{
//Clean up...
//Log...
//Throw new exception
}
Option B:
neededValue V;
MyClass C = new MyClass();
C.SomeParam = XXX;
try
{
C.Execute();
}
catch
{
//Clean up...
//Log...
//Throw new exception
}
V = C.SomeParam2;
I know both will work, but which is nicer and easiest to read?

hey those are NOT the same thing, in the first case V = C.SomeParam2; will never be executed in case of exception while in the second case it will always be executed.
More than that, your example of catch block usage is deeply wrong, always put the exception object after the catch and log somewhere with a logging framework what has happended, then react and handle the exception if you can, and only if it makes sense, or throw it or don't catch it at all and your calling code will catch it.

I would say option B is easier to read and more practical because you will know later that the Execute can throw and Exception.
They are not the same, in option B if you handle the exception then your B variable will be set too and not only if your Execute succeeds.
And you should always specify with the catch block what kind of exception you are catching and so you can handle it and/or Log it correctly.

I would say option a is more readable. And is certainly how I would do it especially.

Well both will work fine
But make use of second one if you wan to use MyClass object outside the try catch block.
and
In first one scope of MyClass object is upto try block only.
So its depends on your requirement how you can use one of the two.

I think you should include in your try block all the code having to do with the small task you are trying to accomplish. However, sometimes you NEED to define certain variables before you enter the try block. For instance, you always want to define InputStreams and OutputStreams before the try block so you can close them in your finally block.

It depends on basically one question. Do you want V to be assigned the value of C.SomeParam2 if the Execute method fails, and throws an exception?
If you don't want it to be assigned when it fails, go for A, if you want it to be assigned regardless of how Execute turned out, go for B.

Related

Use of unassigned local variable on finally block

When could i in this example be unassigned?
int i;
try
{
i = 2;
}
catch
{
i = 3;
}
finally
{
string a = i.ToString();
}
You could get a ThreadAbortException before i=2 runs, for example. Anyway, the C# compiler is not exceptionally smart, so it's easy to fool with contrived examples like the above one. It doesn't have to recognize every situation, and if it's not sure it is assigned, even if you are sure, it will complain.
EDIT: I was a bit quick on my first assumption. So to refine it, here's what I think. Code is guaranteed to run in order, or if an exception happens, it will jump to the handlers. So i=2 may not run if an exception happens before that. I still claim that a ThreadAbortException is one of the few reasons why this can happen, even you have no code which could produce exceptions. Generally, if you have any number of different exception handlers, the compiler cannot know in advance which one will run. So it doesn't try to make any assumptions about that. It could know that if 1) there is only 1 catch block and 2) it is typeless, then, and only then, that one catch block is guaranteed to run. Or, if there were multiple catch handlers, and you assigned your variable in every one of them, it could also work, but I guess the compiler doesn't care about that either. However simple it may seem, it is a special case, and the C# compiler team has a tendency to ignore those special cases.
It's highly unlikely it will happen with the example you have posted. However, the compliler is going to be 'helpful' in this situation. As Hadas said, just initialize i to 0.
There are lots of code samples that one can write in which it is provably the case that a variable is assigned but that the compiler simply cannot prove that it is definitely assigned.
Just consider this much simpler case:
int i;
if ((bool)(object)true)
i = 0;
Console.WriteLine(i);
It is provably impossible for that case to ever access an unassigned i as well, yet it won't compile.
It is also provably impossible for the compiler to solve this problem in the general case. There are cases where it can prove a variable is certainly not definitely assigned, and there are cases where it can prove it definitely is assigned, but there are also cases where it just doesn't know either way. In those cases it chooses to fail, because it sees a few false positive errors as less harmful than false negatives.
To speak more about your specific case; you're saying that if a variable is assigned in both the try and catch blocks it is definitely assigned. While that may be true of your specific code, it's certainly not true in the general case. You need to consider exceptions that aren't handled by the catch block (even in your case, where none is specified, exceptions such as a stack overflow or out of memory won't be caught), you need to consider the catch block itself throwing an exception (again, it won't happen in your case, but the compiler would need to prove that to compile the code).
I think it would help if you to look at another type besides a primitive. Consider:
int i;
MyClass ed = new MyClass();
try
{
int newI = ed.getIntFromFunctionThatWillThrow();
i = newI;
}
catch (Exception e)
{
i = 3;
// do some abortion code.
}
finally
{
string a = i.ToString();
...
}
So in this block of code, there is no lexicographical guarantee for any one branch of execution. You have two (at least) branches to consider: The try-finally branch, and the try-catch branch. Since the function "getIntFromFunctionThatWillThrow" is going to throw (See what I did there?) i will be left unassigned, even though I try to use it later. However, that isn't something that is recognized until after runtime, like I have no idea what section of code this will get into if I have no inside information about the member on ed. So the compiler has no idea what value i will be. It only knows that it exists, and is of type int.
If it was an issue, a fix is to set i an initial value, this will suppress the error.
I hope this helps somewhat!

How to test a swallowed exception

I spent some time looking for a way of resolving my issue but with no success!
Here is my problem: I have got some code that does the following:
public void DoSomething(){
try{
DoStuffThatCanThrowException();
}catch(Exception e){
// Do nothing...
}
}
As you can see, the try catch block swallows all exceptions that can be thrown in the DoStuffThatCanThrowException().
I am trying hard to think of a way to write a unit test that basically ensures that no exception is thrown in the DoStuffThatCanThrowException(). The difficulty here is that I can neither change the try catch block nor the DoStuffThatCanThrowException() method.
Any hints are highly appreciated.
EDIT
One important detail I forgot to mention, I can not call DoStuffThatCanThrowException directly as it is internal and so is not visible from the outside world.
Can't you just call DoStuffThatCanThrowException from a unit test itself, therefore not being surrounded by try...catch at all?
Edit: Just seen that your method is internal. I'd suggest for the purposes of your test you make a public method which wraps it. That way you can test things temporarily. Once you are sure that the method cannot fail you have no further need for the try...catch in the first place.
Sorry for mess with the answer, maybe reflection will help you to dig in?
ClassContainingInternalMethod cl = new ClassContainingInternalMethod ();
//any private or internal method you want here.
MethodInfo dynMethod =
cl.GetType().GetMethod("DoSomeStuff", BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(cl, new object[] {});
Can you call DoStuffThatCanThrowException() directly? If not, make a subclass of the original class that contains that try catch block and call it from there without the catch block.
class ClassUnderTest extends OriginalClass
{
#Override
public void functionToTest()
{
DoStuffThatCanThrowException()
}
}
Also, testing for the absence of exceptions is difficult. You need to find all the potential exceptions that can be thrown and test around that. Even then, all you're saying is that "give these tests, no exceptions were thrown". This is less powerful than saying "Exceptions will never be thrown", but is usually good enough.
Add a positive assert immediately after the call to DoStuffThatCanThrowException(), within the try block. If an exception occurs then the assert won't be executed. Or, add a negative assert inside the catch block. Not sure if this answers your question; it's not very clear.

Exiting a Class From C# Using a Catch

I'm looking for the best method of handling errors in a c# winforms class that I have. The gist of the application is that it has a data analyzer that analyzes the data for statistics and other such stuff. However, I'm looking for the proper way of handling an ABORT.
For example, I have the class called Analyzer
namespace PHOEBE
{
public class Analyzer
{
public Analyzer(){
DoAnalysis();
DoFurtherAnalysis();
}
public class DoAnalysis(){
try{
Convert.ToInt32("someNumber...."); //obviously fails..
}
catch{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
}
Obviously, when DoAnalysis() is called, there will be an error that occurs. The catch block will catch the exception. However, when this catch occurs, it will return to the constructor and run DoFurtherAnalysis(). This is a problem.
I know that you could do return values from each method where each value indicates a certain outcome (ie. 1 = success, 0 = fail). However, a lot of the methods I call, use return values already. I could also use a boolean that gets flagged when an error occurs and check that value before calling the next method from the constructor, but checking this value each time is annoying and repetitive.
I was really hoping for some sort of like "abort mechanism" that I could use. Is there any other ways of working around this? Any interesting work-arounds for this?
Assume this class is being called from a form.
Just let the exception propagate up - you should only catch the exception if you can actually handle it. Exceptions are the "abort mechanism" in .NET. You're currently swallowing the signal that everything's gone wrong, and returning as if all were well.
Generally I find catching exceptions to be pretty rare - usually it's either at the top level (to stop a whole server from going down just because of one request) or in order to transform an exception of one kind into another in order to maintain appropriate abstractions.
I was really hoping for some sort of like "abort mechanism" that I
could use. Is there any other ways of working around this? Any
interesting work-arounds for this?
Yes, there is. It is called exception handling.
Let's rewrite your code:
namespace PHOEBE
{
public class Analyzer
{
public Analyzer()
{
try
{
DoAnalysis();
DoFurtherAnalysis();
}
catch
{
//ERROR OCCURRED, ABORT ALL ANALYSIS
return;
}
}
public class DoAnalysis()
{
Convert.ToInt32("someNumber...."); //obviously fails..
}
}
Now, the constructor will abort and not run the second method since the exception will "bubble through" and be catched where you want it.
On an unrelated note: Please try to catch as specific exceptions as possible, in this case a FormatException
You are subverting the existing "abort" mechanism by catching an exception that you are not doing anything about and swallowing it.
You should not use a try{}catch{} block in this case and let the exception bubble up and cause the application to abort.
The easiest work-around is don't catch the exception. If that were to happen, it'd go straight past the DoFurtherAnalysis() function and out to the original caller.
Don't see anything anoying in returning and checking bool return value from the function. It's much much better solution then having some tricky internal state management, that you for sure will messed up after a couple of months when you return to your code.
Make code sumple and streghtforward. It's not anoying, it's good.
In your specific case if you want just abort everything, just do not catch exception it will abort your program.
use a try...catch in the constructor?
Well, you've got several issues mixed up here. First, it looks like you do possibly-very expensive processing from your constructor. If that processing can throw, you really don't want to call it from your constructor becuase you don't even have the option of returning an error code.
Second, (and you'll read in many threads here,) how you handlee errors really depends on the application and expectation of your users. Some errors could be corrected by changes to inputs. Others might happen in the middle of the night if analysis takes a long time and you might want to continue with another analysis, logging this error.
So I think we're really going to punt back to you for more information about the above.
You could just move DoFurtherAnalysis(); into the the try block
And I would do this entire process somewhere other than the constructor.
Only thing I ever do in the constructor is initialize properties.

Why does Try-Catch require curly braces

Just curious: Why is the syntax for try catch in C# (Java also?) hard coded for multiple statements? Why doesn't the language allow:
int i;
string s = DateTime.Now.Seconds % 2 == 1 ? "1" : "not 1";
try
i = int.Parse(s);
catch
i = 0;
The example is for trivial purposes only. I know there's int.TryParse.
Consider the fact that there are really three (or more) code blocks in play here:
try {}
catch (myexcption)
{}
catch (myotherexception)
{}
finally
{}
Keep in mind that these are in the scope of a larger context and the exceptions not caught are potentually caught further up the stack.
Note that this is basically the same thing as a class construct that also has the {} structure.
Say for instance you might have:
try
try
if (iAmnotsane)
beatMe(please);
catch (Exception myexception)
catch (myotherexception)
logerror("howdy")
finally
NOW does that second catch belong to the first or the second try? What about the finally? SO you see the optional/multiple portions make the requirement.
UPDATE: This question was the subject of my blog on December 4th, 2012. There are a number of insightful comments on the blog that you might also be interested in. Thanks for the great question!
As others have noted, the proposed feature introduces ambiguities that are confusing. I was interested to see if there were any other justifications for the decision to not support the feature, so I checked the language design notes archive.
I see nothing in the language design notes archive that justifies this decision. As far as I know, C# does it that way because that's how other languages with similar syntax do it, and they do it that way because of the ambiguity problem.
I did learn something interesting though. In the initial design of C# there was no try-catch-finally! If you wanted a try with a catch and a finally then you had to write:
try
{
try
{
XYZ();
}
catch(whatever)
{
DEF();
}
}
finally
{
ABC();
}
which, not surprisingly, is exactly how the compiler analyzes try-catch-finally; it just breaks it up into try-catch inside try-finally upon initial analysis and pretends that's what you said in the first place.
More or less, this is a play on the dangling else problem.
For example,
if( blah )
if ( more blah )
// do some blah
else
// no blah I suppose
Without curly braces, the else is ambiguous because you don't know if it's associated with the first or second if statement. So you have to fallback on a compiler convention (e.g. in Pascal or C, the compiler assumes the dangling else is associated with the closest if statement) to resolve the ambiguity, or fail the compile entirely if you don't want to allow such ambiguity in the first place.
Similarly,
try
try
// some code that throws!
catch(some blah)
// which try block are we catching???
catch(more blah )
// not so sure...
finally
// totally unclear what try this is associated with.
You could solve it with a convention, where catch blocks are always associated with the closest try, but I find this solution generally allows programmers to write code that is potentially dangerous. For example, in C, this:
if( blah )
if( more blah )
x = blah;
else
x = blahblah;
...is how the compiler would interpret this if/if/else block. However, it's also perfectly legitimate to screw up your indenting and write:
if( blah )
if( more blah )
x = blah;
else
x = blahblah;
...which now makes it appear like the else is associated with the outer if statement, when in fact it is associated with the inner if statement due to C conventions. So I think requiring the braces goes a long way towards resolving ambiguity and preventing a rather sneaky bug (these sorts of issues can be trivial to miss, even during code inspection). Languages like python don't have this issue since indentation and whitespace matter.
If you assume that the designers of C# simply choose to use the same syntax as C++ then the question becomes why are braces necessary with single statements try and catch blocks in C++. The simple answer is that Bjarne Stroustrup thought the syntax was easier to explain.
In The Design and Evolution of C++ Stroustrup writes:
"The try keyword is completely redundant and so are the { } braces except where multiple statements are actually used in a try-block or a handler."
He goes on to give an example where the try keyword and { } are not needed. He then writes:
"However, I found this so difficult to explain that the redundancy was introduced to save support staff from confused users."
Reference:
Stroustrup, Bjarne (1994). The Design and Evolution of C++. Addison-Wesley.
The first think I can think of is that the curly braces create a block with its own variable scope.
Look at the following code
try
{
int foo = 2;
}
catch (Exception)
{
Console.WriteLine(foo); // The name 'foo' does not exist in the current context
}
foo is not accessible in the catch block due to the variable scoping. I think this makes it easier to reason about whether an variable has been initialized before use or not.
Compare with this code
int foo;
try
{
foo = 2;
}
catch (Exception)
{
Console.WriteLine(foo); // Use of unassigned local variable 'foo'
}
here you can not guarantee that foo is initialized.
try // 1
try // 2
something();
catch { // A
}
catch { // B
}
catch { // C
}
does B catches try 1 or 2?
I don't think you can resolve this unambiguously, since the snippet might mean:
try // 1
{
try // 2
something();
catch { // A
}
}
catch { // B
}
catch { // C
}
try // 1
{
try // 2
something();
catch { // A
}
catch { // B
}
}
catch { // C
}
Probably to discourage overuse. A try-catch block is big and ugly, and you're going to notice when you're using it. This mirrors the effect that a catch has on your application's performance - catching an exception is extremely slow compared to a simple boolean test.
In general you should avoid errors, not handle them. In the example you give, a much more efficient method would be to use
if(!int.TryParse(s, out i))
i=0;
The rational is that it's more maintainable (easier to change, less likely to break, ergo higher quality):
it's clearer, and
it's easier to change because if you need to add a line to your blocks you don't introduce a bug.
As to why exception handling is different than conditional expressions...
If/Else is conditional upon an expression to use one of two (or more If/Else if/Else) paths in the code
Try/Catch is part of exception handling, it is not a conditional expression. Try/Catch/Finally operates only when an exception has been thrown inside the scope of the Try block.
Exception handling will traverse up the stack/scope until it finds a Catch block that will catch the type of exception that was thrown. Forcing scope identifiers makes this check for blocks simplified. Forcing you to scope when dealing with exceptions seems like a good idea, it also is a good indication that this is part of exception handling rather than normal code. Exceptions are exceptions, not something you really want happening normally but know can happen and want to handle when they do happen.
EDIT: There is one more reason which I can think of, is that CATCH is mandatory after a TRY unlike ELSE. Hence there needs to be definite way to define the TRY block.
Another way of looking at this…
Given all the maintenance problem that have been created by “if”, “while”, “for” and “foreach” statements without bases, a lot of companies have coding standards that always require bases on statements that act on a “block”.
So they make you write:
if (itIsSo)
{
ASingleLineOfCode();
}
Rather then:
if (itIsSo)
ASingleLineOfCode();
(Note as indenting is not checked by the compiler, it can't be depended on to be right)
A good case could be made for designing a language that always require the bases, but then too many people would have hated C# due to having to always use the bases. However for try/catch there was not an expectation of being able to get away without using the bases, so it was possible to require them without to many people complaining.
Given a choose I would much rather have if/endIf (and while/endWhile) as the block delimiters but the USA got its way on that one. (C got to define what most languages look like rather than Module2, afterall most of what we do is defined by history not logic)
The simplest (I think) answer is that each block of code in C/C++/C# requires curly braces.
EDIT #1
In response to negative votes, directly from MSDN:
try-catch (C# Reference)
The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions.
As per definition says, it is a block, so it requires curly braces. That is why we cannot use it without { }.

Does an exception inside a TRY block break its execution?

I'm importing several fields, and that is, about 25 lines of code each importing one field (in my case, there's really no other way).
It's in a try-catch block, but there are some times, that this field doesn't exist in the source, but I have to get the rest.
from 20.
I get 10
the 11th one doesn't exist (exception)
I still need from 12 to 20.
In case I don't want to test the existence one by one, I'd like to know how try works. in case of an exception, it doesn't execute the rest, right? what could fit for me ?
obs: it's way more than 20, I want a smart-and-non-poluting solution for it.
If an exception occurs within a try block, nothing after the exception will get executed. So if the exception happens on item 11, items 12 - 20 will not get executed. The execution will jump from item 11 to the catch block and then to the finally block if there is a finally block.
From what your question has said, you get the exception when a field doesn't exist. I recommend checking to see if the field exists, and then do the operation. I do NOT recommend using a try catch as a means to check an existence condition. Try catches should be for error handling, and if you do get an error, you normally do not want to continue normal execution. If you don't like the idea of checking the condition on each line, or there is no other way to check it other than catching an exception, then I suggest making a help function with the try catch in that
boolean checkField(field){
try{/* do operation on field*/}
catch(Exception e){return false;}
return true;
}
void main(){
if !(checkField(field1)) return;
else if !(checkField(field2)) return;
.
.
.
}
Yes, an exception does break the try block - that is the way to handle them.
If you want to keep going, you need try/catch for every field. This doesn't mean writing it 20 times, far from it, refactor your code:
Add a function that gets the field (as string?) and tries to return a value.
Create a new class and define every field as an object.
Don't throw an exeption at all - if this is a common scenario, don't throw an exception! Add a check before you read the value. Again, moving this to a function will help.
Here is try-catch-finally
I would still recomend to check fro the existance of the field. This is cleaner, and more correct.
Exceptions in a loop will be a lot slower than just checking for validity.
When an exception occurs within a try block, it will jump staright out to the catch block (if there isn't a catch block, it will jump into the finally block and the exception will be bubbled up. So, the code in the try block AFTER the error occurs will not be executed.
Either:
1) Check the existence of the field before each attempt
2) wrap each individual field import in it's own try...catch
I'd go for 1), prevent exceptions happening in the first place.
If you refactor/split out code to check the existence of a field into a separate reusable method, it's not really that much effort.

Categories