Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does trycatch hurt the memory/CPU?

Tags:

c#

exception

so I am interested in the c# side of it - but I am tagging c++ as the concept exists there and I am not over the 'finally' keyword. So anyway - are there any benchmarks online about how try-catch would slow down or will use more memory than simple 'if-else' or other code?? For instance, now I am writing a code and using Streamwriter which shows 7 possible exceptions when you hold your mouse over it...so would anyone claim that it will be faster if i write something like:

//////////////
if(path is not too long)
{ if(file exists)
{ if(nothing else uses the file)
{ if(user is authorized)
}}}
////////////

You have 7 conditions and you can use instead just try-catch - not to mention that these conditions cannot be simplified to a single if statement.

10x!

like image 633
nick Avatar asked Feb 22 '23 18:02

nick


1 Answers

try/catch has a slight performance cost if the exception occurs, but compared to file access the cost is not worth worrying about.

More important is that try/catch is correct, the nested ifs are not, because the filesystem is a shared resource that can be modified asynchronously. Handling the error or exception result of actually opening the file is the only way to avoid a race condition.

See

  • http://blogs.msdn.com/b/jaredpar/archive/2009/12/10/the-file-system-is-unpredictable.aspx
  • http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx
  • how can you easily check if access is denied for a file in .NET?

These examples all use files, but there's a general principle here for shared resources.

like image 187
Ben Voigt Avatar answered Mar 07 '23 15:03

Ben Voigt