Why can't I use code like this ?
int i = 0;
try i = int.Parse("qwerty");
catch throw;
try i = int.Parse("qwerty");
catch;
finally Log.Write("error");
And should write like this
int i = 0;
try { i = int.Parse("qwerty"); } catch { throw; }
try { i = int.Parse("qwerty");}
catch {}
finally {Log.Write("error");}
PS:
I can use if-else statement without {}. Why should I use them with try-catch(-finally) statement ? Is there any meaningful reason ?
Is it only because that some people think that code is hard to read ?
Several months ago I asked that question on russian programming forum but I got no satisfactory answer ...
Yes it does not have throw or rethrow activity. I put the try catch in the processing part. Then I would recommend you to put a debugger inside catch and see which activity or segment is throwing the exception.
You can also omit the arguments on the catch block entirely. In this case, the catch block will catch all exceptions, regardless of their type. Because you don't declare an exception variable, however, you won't have access to information about the exception.
If an inner try statement does not have a catch -block, the enclosing try statement's catch -block is used instead. You can also use the try statement to handle JavaScript exceptions.
With a try catch, you can handle an exception that may include logging, retrying failing code, or gracefully terminating the application. Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead.
That's what the language designers decided.
In either case, even a single line if
is dangerous - people add lines expecting them to be included in the if
, which of course, as they are not in {}
, they are not.
C# probably made the braces a requirement because C++ did. My guess as to why they're required in C++ is that it makes it easier to write nested and multiple catch blocks without making mistakes. The braces add an extra level of scope, which can be convenient, but I can't think of a reason why it would be required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With