capture using(StreamWriter wr = new StreamWriter()) exceptional

  • Thread starter Thread starter kids_pro
  • Start date Start date
K

kids_pro

Hi there,

using(StreamWriter wr = new
StreamWriter(filename,false,Encoding.UTF8,1024)){}

Will the line above throw any exception when it can't create file?
What is the best way to capture it exceptions?

Cheers,
Kids
 
kids_pro said:
Hi there,

using(StreamWriter wr = new
StreamWriter(filename,false,Encoding.UTF8,1024)){}

Will the line above throw any exception when it can't create file?
What is the best way to capture it exceptions?

"using" is basically a try/finally block, thus all exceptions thrown by
StreamWriter as documented on MSDN will bubble up to the next exception
handler. If you want to deal with certain exceptions right there, it's
easier to use a classical try/catch/finally.


Cheers,
 
Wow amazing.
I better not use the using statement forever, right?
Cuz there is no good to write a few line and capture 9 exceptions :(
 
kids_pro said:
Wow amazing.
I better not use the using statement forever, right?
Cuz there is no good to write a few line and capture 9 exceptions :(

It depends on your exception handling strategy -- hopefully you have one ;-)
 
kids_pro said:
Unfortunately I haven't got one yet.
Would you recommend a few good practise?

This is a very complex topic, and I guess the world is still waiting for
ultimate treatise on exception handling. Here is a nice checklist, though
(see http://www-106.ibm.com/developerworks/java/library/j-ejbexcept.html):
1. If you can't handle an exception, don't catch it.

2. If you catch an exception, don't swallow it.

3. Catch an exception as close as possible to its source.

4. Log an exception where you catch it, unless you plan to rethrow it.

5. Structure your methods according to how fine-grained your exception
handling must be.

6. Use as many typed exceptions as you need, particularly for application
exceptions.

Point 1 is obviously in conflict with Point 3. The practical solution is a
trade-off between how close to the source you catch an exception and how far
you let it fall before you've completely lost the intent or content of the
original exception.
<<

Also, the chapter on exceptions in Richter's .NET Framework Programming (MS
Press) is highly recommended.

Cheers,
 
Back
Top