Sign in to follow this  

[.net] Exceptions, catch all in one or not?

This topic is 4722 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello all! :) I have a question regarding exceptions.(C#) What is better, every exception listed:
       try
       {
           FileStream file = File.OpenRead( this.folderName + Path.DirectorySeparatorChar + fileName );
       }
       catch( DirectoryNotFoundException )
       {
           throw;
       }
       catch( FileNotFoundException )
       {
           throw;
       }
      // ...


or:
       try
       {
           FileStream file = File.OpenRead( this.folderName + Path.DirectorySeparatorChar + fileName );
       }
       catch
       {
           throw;
       } 
      // ...


IN such cases where I want to catch the most important. ( Null reference exception too?hmm.. ) Thank you! :)

Share this post


Link to post
Share on other sites
If you handle two exceptions types differently you should catch them seperately. If you handle all exception types the same way you should catch them all together. If you aren't handling the exception at all, you shouldn't have a try/catch block in the first place.

Share this post


Link to post
Share on other sites
Well, I don't want to let it crash because of an exception.

OpenRead may throw:

/// <exception cref="DirectoryNotFoundException"></exception>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="UnauthorizedAccessException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="PathTooLongException"></exception>
/// <exception cref="NotSupportedException"> If the path has an invalid format. </exception>
/// <exception cref="ArgumentException"> If the fileName/folder contains invalid arguments/characters. </exception>
/// <exception cref="ArgumentNullException"> If the fileName/folder is null. </exception>





I wonder why engines like Axiom don't catch exeptions at all.. ( last build I saw )




Thank you for your help SiCrane. ^^,

Share this post


Link to post
Share on other sites
Quote:
Original post by Riddle
Well, I don't want to let it crash because of an exception.


The rule is to handle exceptions at the point in the code where you can do something about the problem that caused the exception. Which may not give you much of a hint, I'll grant you that much.

Quote:

I wonder why engines like Axiom don't catch exeptions at all.. ( last build I saw )


It could be because many programmers don't know how to use exceptions in the first place; or because some of those exceptions they throw are better handled by client code you write.

Share this post


Link to post
Share on other sites
Quote:
Original post by Riddle
Well, I don't want to let it crash because of an exception.

You do realize that code you have doesn't contribute to that goal at all, right? Again, if all your catch block does is rethrow the exception, you might as well not have a catch block in the first place.

Share this post


Link to post
Share on other sites
You'd almost never want to catch ALL exceptions at once.

Using

catch(Exception) {}
// or
catch {}

to handle several exceptions at once is EVIL. Always keep in mind that exceptions like ExecutionEngineException might be thrown somewhere. Simply ignoring the severity of those exceptions is deadly.

Regards,
Andre

Share this post


Link to post
Share on other sites
Well i have catches that catch everything, throughout my engine. I have written a class that handles all exceptions for me, so i simply rethrow the exception, then catch it again inside the calss when it is called.

Works well.

ace

Share this post


Link to post
Share on other sites
[CODE]
try
{
FileStream file = File.OpenRead( this.folderName + Path.DirectorySeparatorChar + fileName );
}
catch( DirectoryNotFoundException )
{
throw;
}
catch( FileNotFoundException )
{
throw;
}
[/CODE]

That´s plainly stupid, if you don´t do anything at the catch block, why catch it and rethrow it instead of letting it unwind alone?, you get exactly the same without polluting your code with 11 extra lines over 1 line

PS: At least you use "throw" instead of "throw e", which starts a new StackTrace ;)

PSS: On topic: catch each concrete exception when you can do somethiung about it, catch all exceptions around the main loop to show a "nice" message to the user and die elegantly

Share this post


Link to post
Share on other sites
In my main function I usually put a try/catch block that can catch any type of exception, and it assumes that these exceptions are fatal. If anywhere I might encounter a non-fatal exception or an exception that needs to be handles differently, I simply add another try/catch block there.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by Riddle
OpenRead may throw:
*** Source Snippet Removed ***

Different exceptions are thrown for different reasons. Getting a ArgumentNullExceptionException from OpenRead means you're sending it incorrect data, i.e. it's a programming error. In general you don't want to catch those.

Other errors are less or more likely to happen. It might be that the user enters an invalid path separator (ArgumentException), enters a file that doesn't exist (FileNotFoundException, DirectoryNotFoundException) or doesn't have access to the file (UnauthorizedAccessException). You might want to catch those errors and let the user retry. Either you do a lot of work and guide the user with different error messages for each of the exceptions, or you simply show MessageBox.Show("Failed to open file, please enter a valid file name", exeception.Message);

More examples... Suppose ArrayList.BinarySearch throws exceptions. Then you might get ArgumentException or InvalidOperationExecption. Those messages typically indicates programming errors. The user can't really do much about such errors. Simply let the program crash if that happens. Possibly you could catch on top level in your application, print the call stack into a log file, and kindly ask the user to send you the logfile. But DON'T put try/catch around each of your ArrayList.BinarySearch calls, that only makes your code hard to read for no reason. Those are the kind of errors your testing should find so the user never sees them.

So what about ExecutionEngineException? I'd say *never* care about such. It indicates a bug in the .Net runtime. You can't do anything at all and it's unlikely to happen.

In most cases you probably don't care about OutOfMemoryExceptions either. On a modern system it will likely not happen. You could however have a top level catch in your message loop.

What you should do is to be aware of that exceptions may be thrown. It's a good habit to use the 'using' statement if you're working with a file or other IDisposable objects.

using (FileStream fs = new FileStream(path))
{
...
fs.SomeOperation();
...
]

That assures that the file is always closed when leaving the code block, even if exceptions are thrown.

Share this post


Link to post
Share on other sites

This topic is 4722 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this